栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

elasticsearch学习3:elasticsearch7.1.6 java api

elasticsearch学习3:elasticsearch7.1.6 java api

package com.thinkgem.jeesite.util.elasticsearch;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.linkedList;
import java.util.List;
import java.util.Map;

import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.modules.lore.entity.Knowledge;
import com.thinkgem.jeesite.modules.sys.utils.HttpClient3;
import com.thinkgem.jeesite.modules.sys.utils.SysUtils;
import com.thinkgem.jeesite.util.elasticsearch.bean.GroupByListItem;
import com.thinkgem.jeesite.util.elasticsearch.jsonFormat.DefaultJsonFormat;
import com.thinkgem.jeesite.util.elasticsearch.jsonFormat.JsonFormatInterface;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
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.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.Timevalue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;


public class ElasticSearchUtil {

   private RestHighLevelClient restHighLevelClient;
   private RestClient restClient;

   private String hostname = "127.0.0.1";
   private int port = 9200;
   private String scheme = "http";
   private String username = "";  //elasticsearch链接的用户名,如果es本身没设置使用用户名密码的,那这里就不用设置
   private String password = "";  //elasticsearch链接的密码,如果es本身没设置使用用户名密码的,那这里就不用设置
   private JsonFormatInterface jsonFormatInterface; //JSON格式化接口。默认使用 DefaultJsonFormat();
   private HttpHost[] httpHosts;

   
   public Map>> cacheMap;
   public int cacheMaxNumber = 100; //如果使用缓存,这里是缓存中的最大条数,超过这些条就会自动打包提交

   
   public ElasticSearchUtil(HttpHost... httpHosts) {
      this.httpHosts = httpHosts;
      cacheMap = new HashMap>>();
      jsonFormatInterface = new DefaultJsonFormat();
   }

   
   public ElasticSearchUtil(String hostname) {
      this.hostname = hostname;
      cacheMap = new HashMap>>();
      jsonFormatInterface = new DefaultJsonFormat();
   }

   
   public ElasticSearchUtil(String hostname, int port, String scheme) {
      this.hostname = hostname;
      this.port = port;
      this.scheme = scheme;
      cacheMap = new HashMap>>();
      jsonFormatInterface = new DefaultJsonFormat();
   }

   
   public ElasticSearchUtil(String hostname, int port, String scheme, String username, String password) {
      this.hostname = hostname;
      this.port = port;
      this.scheme = scheme;
      if(username != null && username.length() > 0) {
         this.username = username;
      }
      if(password != null && password.length() > 0) {
         this.password = password;
      }
      cacheMap = new HashMap>>();
      jsonFormatInterface = new DefaultJsonFormat();
   }

   
   public void setUsernameAndPassword(String username, String password) {
      if(username != null && username.length() > 0) {
         this.username = username;
      }
      if(password != null && password.length() > 0) {
         this.password = password;
      }
   }

   
   public void setCacheMaxNumber(int cacheMaxNumber) {
      this.cacheMaxNumber = cacheMaxNumber;
   }

   
   public void setJsonFormatInterface(JsonFormatInterface jsonFormatInterface) {
      this.jsonFormatInterface = jsonFormatInterface;
   }

   
   public RestHighLevelClient getRestHighLevelClient(){
      if(this.restHighLevelClient == null){
         if(this.httpHosts == null){
            //没有直接传入 httpshosts,那么就是使用单个的
            HttpHost httpHost = new HttpHost(this.hostname, this.port, this.scheme);
            this.httpHosts = new HttpHost[1];
            this.httpHosts[0] = httpHost;
         }
         if(this.username.length() > 0 && this.password.length() > 0) {
            //当前elasticsearch 设置了连接的用户名密码
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));  //es账号密码(默认用户名为elastic)
            this.restHighLevelClient =new RestHighLevelClient(
                  RestClient.builder(this.httpHosts).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                     public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        httpClientBuilder.disableAuthCaching();
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                     }
                  })
            );
         }else{
            this.restHighLevelClient = new RestHighLevelClient(RestClient.builder(this.httpHosts));
         }
      }
      return this.restHighLevelClient;
   }

   
   public RestClient getRestClient(){
      if(this.restClient == null){
         if(this.httpHosts == null){
            //没有直接传入 httpshosts,那么就是使用单个的
            HttpHost httpHost = new HttpHost(this.hostname, this.port, this.scheme);
            this.httpHosts = new HttpHost[1];
            this.httpHosts[0] = httpHost;
         }
         if(this.username.length() > 0 && this.password.length() > 0) {
            //当前elasticsearch 设置了连接的用户名密码
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));  //es账号密码(默认用户名为elastic)
            this.restClient = RestClient.builder(this.httpHosts).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
               public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                  httpClientBuilder.disableAuthCaching();
                  return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
               }
            }).build();

         }
         this.restClient = RestClient.builder(this.httpHosts).build();
      }
      return this.restClient;
   }

   
   public static RestHighLevelClient getStaticRestHighLevelClient(){
      String hostName = SysUtils.getSysConfigValue("ElasticSearchIp","90");
      RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder("172.0.0.1"));
      return restHighLevelClient;
   }


   
   public synchronized void cache(Map params, String indexName){
      List> list = cacheMap.get(indexName);
      if(list == null){
         list = new linkedList>();
      }
      list.add(params);

      if(list.size() >= this.cacheMaxNumber){
         //提交
         boolean submit = cacheSubmit(indexName);
         if(submit){
            //提交成功,那么清空indexName的list
            list.clear();
         }
      }

      //重新赋予cacheMap
      cacheMap.put(indexName, list);
   }

   
   public synchronized boolean cacheSubmit(String indexName){
      List> list = cacheMap.get(indexName);
      if(list == null){
         return true;
      }

      BulkResponse res = puts(list, indexName);
      if(res == null || res.hasFailures()){
         //出现错误,那么不清空list
         return false;
      }else{
         //成功,那么清空缓存中这个索引的数据
         list.clear();
         cacheMap.put(indexName, list);
         return true;
      }
   }

   
   public CreateIndexResponse createIndex(String indexName)  {
      CreateIndexResponse response=null;
      if(existIndex(indexName)){
         response = new CreateIndexResponse(false, false, indexName);
         return response;
      }

      CreateIndexRequest request = new CreateIndexRequest(indexName);
      try {
         response = getRestHighLevelClient().indices().create(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return response;
   }

   public static void log(String text){
      System.out.println(text);
   }

   
   public boolean existIndex(String index){
      GetIndexRequest request = new GetIndexRequest();
      request.indices(index);
      boolean exists;
      try {
         exists = getRestHighLevelClient().indices().exists(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
         return false;
      }
      return exists;
   }

   
   public IndexResponse put(String params, String indexName, String id){
      //创建请求
      IndexRequest request = new IndexRequest(indexName);
      if(id != null){
         request.id(id);
      }
      request.timeout(Timevalue.timevalueSeconds(5));

      IndexResponse response = null;
      try {
         response = getRestHighLevelClient().index(request.source(params, XContentType.JSON), RequestOptions.DEFAULT);

      } catch (IOException e) {
         e.printStackTrace();
      }
      return response;
   }

   
   public UpdateResponse update(String params,String indexName, String id){
      //创建请求
      UpdateRequest request = new UpdateRequest(indexName,id);
      request = request.doc(params, XContentType.JSON);
      request.timeout(Timevalue.timevalueSeconds(5));
      UpdateResponse response = null;
      try {
         response = getRestHighLevelClient().update(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return  response;
   }





   
   public IndexResponse put(String params, String indexName){
      return put(params, indexName, null);
   }

   
   public BulkResponse puts(List> list, String indexName){
      if(list.size() < 1){
         return null;
      }

      //批量增加
      BulkRequest bulkAddRequest = new BulkRequest();
      IndexRequest indexRequest;
      for (int i = 0; i < list.size(); i++) {
         indexRequest = new IndexRequest(indexName);
         indexRequest.source(jsonFormatInterface.mapToJsonString(list.get(i)), XContentType.JSON);
         bulkAddRequest.add(indexRequest);
      }

      BulkResponse bulkAddResponse = null;
      try {
         bulkAddResponse = getRestHighLevelClient().bulk(bulkAddRequest, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return bulkAddResponse;
   }

   public BulkResponse putListObject(List list, String indexName){
      if(list.size() < 1){
         return null;
      }
      //批量增加
      BulkRequest bulkAddRequest = new BulkRequest();
      IndexRequest indexRequest;
      for (int i = 0; i < list.size(); i++) {
         indexRequest = new IndexRequest(indexName);
         String esJson = JsonMapper.toJsonString(list.get(i));
         indexRequest.source(esJson, XContentType.JSON);
         bulkAddRequest.add(indexRequest);
      }

      BulkResponse bulkAddResponse = null;
      try {
         bulkAddResponse = getRestHighLevelClient().bulk(bulkAddRequest, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return bulkAddResponse;
   }


   
   public SearchResponse search(String indexName, SearchSourceBuilder searchSourceBuilder, Integer from, Integer size){
      SearchRequest request = new SearchRequest(indexName);
      searchSourceBuilder.from(from);
      searchSourceBuilder.size(size);
      request.source(searchSourceBuilder);
      SearchResponse response = null;
      try {
         response = getRestHighLevelClient().search(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return response;
   }
   public SearchResponse searchCount(SearchRequest request ){
      SearchResponse response = null;
      try {
         response = getRestHighLevelClient().search(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return response;
   }

   
   public List> search(String indexName, String queryString, Integer from, Integer size, SortBuilder sort){
      List> list = new ArrayList>();

      SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
      if(queryString != null && queryString.length() > 0){
         //有查询条件,才会进行查询,否则会查出所有
         QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(queryString);
         searchSourceBuilder.query(queryBuilder);
      }
      //此处可封装获取高亮

      


      //判断是否使用排序
      if(sort != null){
         searchSourceBuilder.sort(sort);
      }
      SearchResponse response = search(indexName, searchSourceBuilder, from, size);
      if(response.status().getStatus() == 200){
         SearchHit shs[] = response.getHits().getHits();
         for (int i = 0; i < shs.length; i++) {
            Map map = shs[i].getSourceAsMap();
            map.put("esid", shs[i].getId());
            list.add(map);
         }
      }else{
         //异常
      }

      return list;
   }


   
   public List> search(String indexName, String queryString){
      return search(indexName, queryString, 0, 20, null);
   }





   
   public  Map searchById (String indexName, String id){
      GetRequest request = new GetRequest(indexName, id);
      GetResponse response = null;
      try {
         response = getRestHighLevelClient().get(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
         return null;
      }
      if(response.isSourceEmpty()){
         //没有这条数据
         return null;
      }

      Map map = response.getSource();
      //为返回的数据添加id
      map.put("esid",response.getId());
      return map;
   }

   public  static Map getById(String indexName, String id){
      GetRequest request = new GetRequest(indexName, id);
      GetResponse response = null;
      try {
         response = getStaticRestHighLevelClient().get(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
         return null;
      }
      if(response.isSourceEmpty()){
         //没有这条数据
         return null;
      }

      Map map = response.getSource();
      //为返回的数据添加id
      map.put("esid",response.getId());
      return map;
   }

   

   public  AcknowledgedResponse deleteIndex(String indexName) throws IOException {
      DeleteIndexRequest request = new DeleteIndexRequest(indexName);
      AcknowledgedResponse response = getRestHighLevelClient().indices().delete(request, RequestOptions.DEFAULT);
      System.out.println(response.isAcknowledged());
      return response;
   }



   
   public boolean deleteById(String indexName, String id) {
      DeleteRequest request = new DeleteRequest(indexName, id);
      DeleteResponse delete = null;
      try {
         delete = getRestHighLevelClient().delete(request, RequestOptions.DEFAULT);
      } catch (IOException e) {
         e.printStackTrace();
         //删除失败
         return false;
      }

      if(delete == null){
         //这种情况应该不存在
         return false;
      }
      if(delete.getResult().equals(Result.DELETED)){
         return true;
      }else{
         return false;
      }
   }

   
   public List> searchBySqlQuery(String sqlQuery){
      List> list = new ArrayList>();

      String method = "POST";
      //String endPoint = "/_sql";
      String endPoint = "/_xpack/sql";
      Request request = new Request(method, endPoint);
      request.addParameter("Content-Type","application/json");

      request.addParameter("format", "text");
      //request.addParameter("header", "{"WWW-Authenticate":"Basic realm=\"security\" charset=\"UTF-8\""}");

      request.setJsonEntity("{"query":""+sqlQuery+""}");
      try {
         Response response = getRestClient().performRequest(request);
         String text = EntityUtils.toString(response.getEntity());

         JSonObject json = JSONObject.parseObject(text);
         JSonArray columnsJsonArray = json.getJSonArray("columns");
         String columns[] = new String[columnsJsonArray.size()];
         //遍历columns
         for (int i = 0; i < columnsJsonArray.size(); i++) {
            JSonObject columnJsonObject = columnsJsonArray.getJSonObject(i);
            columns[i] = columnJsonObject.getString("name");
         }

         //遍历数据
         JSonArray rowsJsonArray = json.getJSonArray("rows");
         for (int i = 0; i < rowsJsonArray.size(); i++) {
            JSonArray row = rowsJsonArray.getJSonArray(i);

            Map map = new HashMap();
            for (int j = 0; j < row.size(); j++) {
               Object obj = row.get(j);
               if(obj != null){
                  //如果此项不为null,那么加入 map
                  map.put(columns[j], obj);
               }
            }
            list.add(map);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

      return list;
   }

   

   public List> searchByHttpClientSqlQuery(String url,String sqlQuery,String username,String password){

      List> list = new ArrayList<>();
      try {
         String text = HttpClient3.doPostHeaderAndSendJson("http://"+url+"/_sql", "{"query":"" + sqlQuery + ""}",username,password);

         JSonObject json = JSONObject.parseObject(text);
         JSonArray columnsJsonArray = json.getJSonArray("columns");
         String columns[] = new String[columnsJsonArray.size()];
         //遍历columns
         for (int i = 0; i < columnsJsonArray.size(); i++) {
            JSonObject columnJsonObject = columnsJsonArray.getJSonObject(i);
            columns[i] = columnJsonObject.getString("name");
         }

         //遍历数据
         JSonArray rowsJsonArray = json.getJSonArray("rows");
         for (int i = 0; i < rowsJsonArray.size(); i++) {
            JSonArray row = rowsJsonArray.getJSonArray(i);

            Map map = new HashMap();
            for (int j = 0; j < row.size(); j++) {
               Object obj = row.get(j);
               if(obj != null){
                  //如果此项不为null,那么加入 map
                  map.put(columns[j], obj);
               }
            }
            list.add(map);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

      return list;
   }

   
   public List groupBy(String indexName, String field, QueryBuilder queryBuilder){
      SearchRequest searchRequest = new SearchRequest();
      searchRequest.indices(indexName);
      TermsAggregationBuilder aggregation = AggregationBuilders.terms("termsname").field(field+".keyword").order(BucketOrder.count(false)).size(100);
      SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
      searchSourceBuilder.aggregation(aggregation);
      if(queryBuilder != null){
         searchSourceBuilder.query(queryBuilder);
      }
      searchRequest.source(searchSourceBuilder);

      List list = new ArrayList();
      SearchResponse response;
      try {
         response = getRestHighLevelClient().search(searchRequest, RequestOptions.DEFAULT);
         Terms byAgeAggregation = response.getAggregations().get("termsname");
         for (Terms.Bucket buck : byAgeAggregation.getBuckets()) {
            GroupByListItem item = new GroupByListItem();
            item.setName(buck.getKeyAsString());
            item.setCount(buck.getDocCount());
            list.add(item);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

      return list;
   }

   
   public int count(String url,String countSql,String username,String password){
      //List> list = searchBySqlQuery(countSql);
      List> list =searchByHttpClientSqlQuery(url,countSql,username,password);
      if(list!=null&&list.size()>0){
         int count = (Integer) list.get(0).values().stream().findAny().get();
         return count;
      }else{
         return 0;
      }

   }


   @Test
   public void testAdd(){
      String indexName = "testind";
      Map map = new HashMap();
      map.put("username", "赵富强的");
      map.put("age", 17);
      map.put("price", 12.6f);
      map.put("a", true);


      
      List> list = new ArrayList>();
      list.add(map);
      map.put("age", 14);
      list.add(map);
      map.put("age", 15);
      list.add(map);
      map.put("username", "zfq");
      list.add(map);
      list.add(map);

      ElasticSearchUtil es = new ElasticSearchUtil("127.0.0.1");
      if(!es.existIndex(indexName)){
         es.createIndex(indexName);
      }

      BulkResponse ir = es.puts(list, indexName);
      System.out.println(ir);
   }

   public static void main(String[] args) {

      String indexName = "testind";
      Map map = new HashMap();
      map.put("username", "赵的");
      map.put("age", 17);
      map.put("price", 12.6f);
      map.put("a", true);


      
      List> list = new ArrayList>();
      list.add(map);

      ElasticSearchUtil es = new ElasticSearchUtil("172.16.10.90000",9200,"http","elastic","123");
      //ElasticSearchUtil es = new ElasticSearchUtil("localhost");
      if(!es.existIndex(indexName)){
         es.createIndex(indexName);
      }
      final int count = es.count("http://172.16.10.90:9200","select count(1)  from knowledge where state= 3 ","elastic","mycomm123");
      System.out.println(count);
      BulkResponse ir = es.puts(list, indexName);

      System.out.println(ir);


//     QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("age:12 AND a:false");
//     SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.query(queryBuilder);
//    System.out.println(es.searchListData(indexName, searchSourceBuilder, 0, 10).toString());

       
//     System.out.println(es.cacheSubmit(indexName));


//     String method = "GET";
//        String endPoint = "/_sql";
//        Request request = new Request(method, endPoint);
//        request.addParameter("format", "json");
//
//        String sql = "update testind set age = 18 WHERe username = 'zhangqun222'";
//        //String sql = "select * from testind WHERe username = 'zhangqun222'";
//
//        request.setJsonEntity("{"query":""+sql+""}");
//
//        Response response = es.getClient().p
              .performRequest(request);
//

//     RestHighLevelClient
//     RestClient restClient = RestClient.builder(
//                new HttpHost("192.168.31.24", 9200, "http")
//         ).build();
//     try {
//       Response response = restClient.performRequest(request);
//       String text = EntityUtils.toString(response.getEntity());
//       System.out.println(text);
//
//       JSonObject json = JSONObject.parseObject(text);
               parseObject(EntityUtils.toString(response.getEntity()));
//       System.out.println(json);
//       JSonArray columnsJsonArray = json.getJSonArray("columns");
//       String columns[] = new String[columnsJsonArray.size()];
//       //遍历columns
//       for (int i = 0; i < columnsJsonArray.size(); i++) {
//          JSonObject columnJsonObject = columnsJsonArray.getJSonObject(i);
//          columns[i] = columnJsonObject.getString("name");
//          System.out.println(columns[i]);
//       }
//       System.out.println(columns);
//
//       //遍历数据
//       JSonArray rowsJsonArray = json.getJSonArray("rows");
//       for (int i = 0; i < rowsJsonArray.size(); i++) {
//          JSonArray row = rowsJsonArray.getJSonArray(i);
//          System.out.println(row);
//       }
//
//    } catch (IOException e) {
//       e.printStackTrace();
//    }


//     List> lists = es.search("useraction", "", 0, 100, null);
//     List> lists = es.search("useraction", "SELECt username, COUNT(*) as number GROUP BY username");
//     List> lists = es.search(indexName, "SELECT * FROM testind WHERe username='zhangqun222'");
//     for (int i = 0; i < lists.size(); i++) {
//       System.out.println(lists.get(i));
//    }
//     System.out.println(lists.size());
//

    
      boolean b = es.deleteById(indexName, "e7lL5X0BS02zE3K8C11i");
      System.out.println(b);


          


      //List> list = es.search("testind", "sum(*)");
      List> listFind = es.search("testind", "username:赵富强'");

      for (int i = 0; i < listFind.size(); i++) {
         System.out.println(listFind.get(i));
      }

      List> listResult = new ArrayList>();

      // 2、指定查询条件
      SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
      // 2.1、查询条件
      searchSourceBuilder.query(QueryBuilders.matchQuery("contentText", "工号"));
      // 2.2、指定高亮
      HighlightBuilder highlightBuilder = new HighlightBuilder();
      highlightBuilder.field("contentText")
            .preTags("")
            .postTags("");

      searchSourceBuilder.highlighter(highlightBuilder);

      SearchResponse testind = es.search("knowledge", searchSourceBuilder, 0, 10);
      SearchHit[] hits = testind.getHits().getHits();
      // 4、打印
      for (SearchHit hit : testind.getHits().getHits()) {
         HighlightField username = hit.getHighlightFields().get("contentText");
         System.out.println(username);
         Text[] texts=username.getFragments();
         System.out.println(texts[0].toString());
         MapsourceAsMap =hit.getSourceAsMap();
         sourceAsMap.put("id", hit.getId());
         sourceAsMap.put("contentText",texts[0].toString());
         listResult.add(sourceAsMap);
      }
      for (int i = 0; i < listResult.size(); i++) {
         System.out.println(listResult.get(i));
      }
   



      

   }
   @Test
   public  void height() throws IOException {
      //没有直接传入 httpshosts,那么就是使用单个的

      String hostname = "127.0.0.1";
      int port = 9200;
      String scheme = "http";
      HttpHost httpHost = new HttpHost(hostname, port,scheme);
      RestHighLevelClient restHighLevelClient2 = new RestHighLevelClient(RestClient.builder(httpHost));

      String indexName="testind";
      // 1、SearchRequest
      SearchRequest searchRequest = new SearchRequest(indexName);

      // 2、指定查询条件
      SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
      // 2.1、查询条件
      searchSourceBuilder.query(QueryBuilders.matchQuery("age", "15"));
      // 2.2、指定高亮
      HighlightBuilder highlightBuilder = new HighlightBuilder();
      highlightBuilder.field("age", 10)
            .preTags("")
            .postTags("");

      searchSourceBuilder.highlighter(highlightBuilder);
      searchRequest.source(searchSourceBuilder);

      // 3、执行
      SearchResponse resp = restHighLevelClient2.search(searchRequest, RequestOptions.DEFAULT);

      // 4、打印
      for (SearchHit hit : resp.getHits().getHits()) {
         System.out.println(hit.getHighlightFields().get("age"));
      }
   }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/706968.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号