SpringBoot整合ElasticSearch 入門demo學習筆記

石頭城程式猿發表於2020-11-05

1、概述

 Elaticsearch ,簡稱為es,es是一個開源的高擴 展的基於java開發的分散式全文檢索引擎,它可以近乎實時的儲存、檢索資料;本身擴充套件性很好可以擴充套件到上百臺伺服器,處理PB級別的資料。es也使用Java開發並使用Lucene作為其核心來實現所有索引和搜尋的功能,但是它的目的是通過簡單的RESTful API來隱藏Lucene的複雜性,從而讓全文搜尋變得簡單。

 

2、SpringBoot整合ES

pom.xml:引入ES客戶端

<dependency>

<groupId>org.elasticsearch.client</groupId>

<artifactId>elasticsearch-rest-high-level-client</artifactId>

<version>7.4.2</version>

</dependency>

 程式碼框架圖:

 

package com.jason.es.config;

import org.apache.http.HttpHost;

import org.elasticsearch.client.RestClient;

import org.elasticsearch.client.RestHighLevelClient;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class MallElasticSearchConfig {

    @Bean

    public RestHighLevelClient restHighLevelClient()

    {

        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));

        return client;

    }

}


package com.jason.es.bean;

import java.util.Date;

public class Info {

    private int age;

    private double money;

    private String address;

    private Date birthday;

    private String name;

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

    public double getMoney() {

        return money;

    }

    public void setMoney(double money) {

        this.money = money;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    public Date getBirthday() {

        return birthday;

    }

    public void setBirthday(Date birthday) {

        this.birthday = birthday;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

package com.jason.es.bean;

public class ResponseBean {

//狀態碼

    private Integer code;

//返回資訊

    private String message;

//返回的資料

    private Object data;

    public ResponseBean(Integer code, String message, Object data) {

        this.code = code;

        this.message = message;

        this.data = data;

    }

    public Integer getCode() {

        return code;

    }

    public void setCode(Integer code) {

        this.code = code;

    }

    public String getMessage() {

        return message;

    }

    public void setMessage(String message) {

        this.message = message;

    }

    public Object getData() {

        return data;

    }

    public void setData(Object data) {

        this.data = data;

    }

}


package com.jason.es.controller;

import com.alibaba.fastjson.JSONObject;

import com.jason.es.Service.InfoService;

import com.jason.es.bean.ResponseBean;

import org.elasticsearch.client.RestHighLevelClient;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

import java.util.Map;

@RestController

@RequestMapping(value="/info",produces = "application/json;charset=utf-8")

public class InfoController {

    public Logger logger= LoggerFactory.getLogger(InfoController.class);

    @Autowired

    private RestHighLevelClient client;

    @Autowired

    public InfoService infoService;

    @RequestMapping("save")

    public ResponseBean save() throws IOException {

        return infoService.save(client);

    }

    @RequestMapping("query")

    public ResponseBean query(HttpServletRequest request) throws IOException {

        Map<String, String[]> parameterMap = request.getParameterMap();

        return infoService.query(client,parameterMap);

    }

}

package com.jason.es.Service;



import com.alibaba.fastjson.JSONObject;

import com.jason.es.bean.Info;

import com.jason.es.bean.ResponseBean;

import com.jason.util.Sequence;

import org.elasticsearch.action.index.IndexRequest;

import org.elasticsearch.action.index.IndexResponse;

import org.elasticsearch.action.search.SearchRequest;

import org.elasticsearch.action.search.SearchResponse;

import org.elasticsearch.client.RequestOptions;

import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.common.xcontent.XContentType;

import org.elasticsearch.index.query.QueryBuilders;

import org.elasticsearch.search.SearchHit;

import org.elasticsearch.search.SearchHits;

import org.elasticsearch.search.builder.SearchSourceBuilder;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Service;

import java.io.IOException;

import java.util.Date;

import java.util.Map;

@Service

public class InfoService {

    public Logger logger= LoggerFactory.getLogger(InfoService.class);

    public ResponseBean save(RestHighLevelClient client) {

        IndexRequest indexRequest = new IndexRequest("info","info");

//indexRequest.id(""+ Sequence.getNextCurval());

// indexRequest.source("userName", "zhangsan", "age", "18");

        Info info=new Info();

        info.setName("jason");

        info.setAge(18);

        info.setMoney(18);

        info.setAddress("易購樓");

        info.setBirthday(new Date(System.currentTimeMillis()));

        String jsonString = JSONObject.toJSONString(info);

// 必須指定XContentType

        indexRequest.source(jsonString, XContentType.JSON);

        ResponseBean responseBean=null;

// 執行

        try{

            logger.info("--"+client);

            client.index(indexRequest, RequestOptions.DEFAULT);

            responseBean=new ResponseBean(200,"success",null);

        }catch (Exception e)

        {

            e.printStackTrace();

            responseBean=new ResponseBean(300,"exception",e);

        }

        return responseBean;

    }

    public ResponseBean query(RestHighLevelClient client, Map<String, String[]> parameterMap) {

        ResponseBean responseBean=null;

        if(parameterMap==null)

        {

            return responseBean=new ResponseBean(300,"查詢入參為空,請輸入查詢條件重新提交!!!",null);

        }

// 建立檢索請求

        Se

        archRequest searchRequest = new SearchRequest();

// 指定索引

        searchRequest.indices("info");

        String age[]=parameterMap.get("age");

// 指定DSL

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.matchQuery("age", age[0]));

// // 按照年齡的值分佈進行聚合

// searchSourceBuilder.aggregation(AggregationBuilders.terms("aggAge").field("age").size(10));

// // 計算平均薪資

// searchSourceBuilder.aggregation(AggregationBuilders.avg("balanceAvg").field("balance"));



        logger.info("檢索條件"+searchSourceBuilder.toString());

        searchRequest.source(searchSourceBuilder);

// 同步執行(也可以使用非同步)

        SearchResponse searchResponse = null;

        try {

            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            SearchHit[] hits = searchResponse.getHits().getHits();

            responseBean=new ResponseBean(200,"success",hits);

        } catch (IOException e) {

            responseBean=new ResponseBean(300,"exception",e);

        }

        return responseBean;

    }

}

 索引查詢:

 

相關文章