springboot整合jest实现es的全文搜索

 <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>6.3.1</version>
</dependency>
package com.liuchao.esdemo.config;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {

    @Bean
    public JestClient jestClient(){
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                        .Builder("http://192.168.0.117:9200")//连接es的配置
                        .multiThreaded(true).build());

                return factory.getObject();
    }
}

分页信息

package com.liuchao.esdemo.entity;

public class Page {
    //一页显示多少条
    private int pageSize;
    //当前页
    private int pageNum;
    //总共多少条
    private int total;
    //总共多少页
    private int pageTotal;

    public Page(int pageSize,int pageNum,int total){
        this.pageNum=pageNum;
        this.pageSize=pageSize;
        this.total=total;
        this.pageTotal=total%pageSize==0?total/pageSize:(total/pageSize)+1;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getPageTotal() {
        return pageTotal;
    }

    public void setPageTotal(int pageTotal) {
        this.pageTotal = pageTotal;
    }

    public static void main(String[] args) {
       Page page=new Page(3,1,9);
        System.out.println(page.pageTotal);
    }
}

分页查询

package com.liuchao.esdemo.es;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import com.google.gson.JsonObject;
import com.liuchao.esdemo.entity.Page;
import com.liuchao.esdemo.entity.User;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Component
public class EsSearch {
    //索引值 index
    private static final String INDEX="logdemo";
    //这个是文档 type
    private static final String TYPE="user";
    @Autowired
    private JestClient jestClient;

    public JSONObject  allFind(String key,int pageSize,int pageNum){

        //全文搜索并加分页排序
        String json="{\"query\": {\"multi_match\": {\"query\": \""+key+"\",\"fields\": [\"user_name\",\"salt\",\"open_id\"]}},\"size\":\""+pageSize+"\",\"from\":\""+(pageNum-1)*pageSize+"\",\"sort\":[{\"create_time\":{\"order\":\"desc\"}}]}\n";
        Search search = new Search.Builder(json).addIndex(INDEX).addType(TYPE).build();
        JSONObject returnObject=null;
        try{
            //查询es执行查询语句
            SearchResult result = jestClient.execute(search);
            //得到返回结果
            JsonObject jsonObject = result.getJsonObject();
            returnObject = toObject(jsonObject, pageSize, pageNum);
            return  returnObject;
        }catch (Exception e){
            e.printStackTrace();
        }
            return returnObject;
    }

    //解析返回结果 拼凑返回结果带分页信息
    public  JSONObject toObject(JsonObject jsonObject,int pageSize,int pageNum){
        JSONObject returnObject=new JSONObject();
        List<JSONObject> list=new ArrayList<>();
        JsonObject hits = jsonObject.getAsJsonObject("hits");
        JsonObject total = hits.getAsJsonObject("total");
        JsonElement value = total.get("value");
        int totleCount = value.getAsInt();
        Page page=new Page(pageSize,pageNum,totleCount);
        returnObject.put("page",page);
        returnObject.put("datas",list);
        JsonArray hits1 = hits.getAsJsonArray("hits");
        if(StringUtils.isEmpty(hits1)){
            return returnObject;
        }
        Iterator<JsonElement> iterator = hits1.iterator();
        while (iterator.hasNext()){
            JsonElement next = iterator.next();
            JsonObject asJsonObject = next.getAsJsonObject();
            JsonElement source = asJsonObject.get("_source");
            String s = source.toString();
            //User user = JSONObject.parseObject(s, User.class);
            //list.add(user);
            JSONObject user = JSONObject.parseObject(s);
            list.add(user);
        }
        return returnObject;

    }

}

jest查询返回的json是es的查询结果所以要解析 (主要要的数据是 hits下面total 的value值 和 hits下面的_source 的所有的值)

#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
        "_index" : "logdemo",
        "_type" : "user",
        "_id" : "3",
        "_score" : null,
        "_source" : {
          "salt" : "4d0149865fed4c26bbee36a0f517b378",
          "open_id" : "中华人民共和国",
          "@version" : "1",
          "create_time" : "2019-03-12T16:00:00.000Z",
          "@timestamp" : "2020-01-08T07:35:00.211Z",
          "id" : 3,
          "user_name" : "lisi",
          "password" : "ce6ae203f56aa7eac8d3b97d3f6588e9"
        },
        "sort" : [
          1552406400000
        ]
      }
    ]
  }
}

猜你喜欢

转载自www.cnblogs.com/dkws/p/12167295.html