snake107

ElasticSearch实战

springboot整合elasticsearch

1、Jest介绍

Jest是Elasticsearch 的Java Http Rest 客户端。

ElasticSearch已经具备应用于Elasticsearch内部的Java API,但是Jest弥补了ES自有API缺少Elasticsearch Http Rest接口客户端的不足。

2、 Jest优势概括如下:

1)提供Restful API, 原生ES API不具备;
2)若ES集群使用不同的ES版本,使用原生ES API会有问题,而Jest不会;
3) 更安全(可以在Http层添加安全处理)。

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;
    }
}
posted @ 2019-11-26 22:31  爱喝奶茶的皮卡丘  阅读(223)  评论(0编辑  收藏  举报