ElasticSearch實戰

springboot整合elasticsearch

一、Jest介紹

Jest是Elasticsearch 的Java Http Rest 客戶端。java

ElasticSearch已經具有應用於Elasticsearch內部的Java API,可是Jest彌補了ES自有API缺乏Elasticsearch Http Rest接口客戶端的不足。spring

二、 Jest優點歸納以下:

1)提供Restful API, 原生ES API不具有;
2)若ES集羣使用不一樣的ES版本,使用原生ES API會有問題,而Jest不會;
3) 更安全(能夠在Http層添加安全處理)。apache

jestclient和ES創建的鏈接爲長鏈接
POM
<!-- 工具類 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>6.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.4.3</version>
        </dependency>
application.yml
spring:
  elasticsearch:
    jest:
      uris: http://192.168.8.105:9200
Service代碼
package com.suoron.springboot.service.impl;

import com.suoron.springboot.entity.GoodsEntity;
import com.suoron.springboot.service.GoodsSearchService;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import io.searchbox.indices.CreateIndex;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.search.MultiMatchQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GoodsSearchServiceImpl implements GoodsSearchService {

    @Autowired
    JestClient jestClient;


    ///建立index
    public void createIndex(String index) {
        try {
            JestResult jestResult = jestClient.execute(new CreateIndex.Builder(index).build());
            System.out.println("createIndex:{}" + jestResult.isSucceeded());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 刪除文檔
     */
    public boolean deleteDoc(String recordId, String indexName, String indexType) {
        Delete.Builder builder = new Delete.Builder(recordId);
        Delete delete = builder.index(indexName).type(indexType).build();
        try {
            JestResult result = jestClient.execute(delete);
            if (result != null && !result.isSucceeded()) {
                throw new RuntimeException(result.getErrorMessage()+"刪除文檔失敗!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void testSearch(){
        //查詢表達式
        String json="{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"name\" : \"100\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        //構建搜索功能
        Search search = new Search.Builder(json).addIndex("goods").addType("goods").build();

        try {
            SearchResult result = jestClient.execute(search);
            System.out.println(result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入或更新文檔
     */
    public boolean insertOrUpdateDoc(String indexId, Object indexObject, String indexName, String indexType) {
        Index.Builder builder = new Index.Builder(indexObject);
        builder.id(indexId);
        builder.refresh(true);
        Index index = builder.index(indexName).type(indexType).build();
        try {
            JestResult result = jestClient.execute(index);
            if (result != null && !result.isSucceeded()) {
                throw new RuntimeException(result.getErrorMessage()+"插入更新索引失敗!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean testEsRestClient() {

        createIndex("goods");  //建立索引庫
        for (int i=0;i<10;i++){   //添加數據
            GoodsEntity goodsEntity = new GoodsEntity();
            goodsEntity.setId(i);
            goodsEntity.setName("測試商品"+i);
            goodsEntity.setPrice(11.01+i);

            insertOrUpdateDoc(""+i,goodsEntity,"goods","goods");
        }
        //刪除記錄
        deleteDoc("1","goods","goods");

        //修改記錄
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setId(2);
        goodsEntity.setName("測試商品"+2);
        goodsEntity.setPrice(999.99);
        insertOrUpdateDoc("2",goodsEntity,"goods","goods");

        //搜索商品
        testSearch();

        return true;
    }
}
相關文章
相關標籤/搜索