ElasticSearch7.2学习—springboot集成elasticsearch

elasticsearch-rest-high-level-client使用

  • ES常用Java Client API
    • 1.REST API
    • 2.Transport 连接
    • Java REST Client介绍
      • 1. ES提供了两个JAVA REST client 版本
      • 2. Java Low Level REST Client 说明
      • 3. Java High Level REST Client 说明
  • springboot集成
  • 总结

ES常用Java Client API

1.REST API

http请求,例如,浏览器请求get方法;利用Postman等工具发起REST请求;java 发起httpClient请求等。

2.Transport 连接

socket连接,用官方提供的TransPort客户端,底层是netty。

注意:ES的发展规划中在7.0版本开始将废弃 TransportClient,8.0版本中将完全移除 TransportClient,取而代之的是High Level REST Client。

官网可以了解详情:

https://www.elastic.co/guide/en/elasticsearch/client/index.html

Java REST Client介绍

1. ES提供了两个JAVA REST client 版本

Java Low Level REST Client: 低级别的REST客户端,通过http与集群交互,用户需自己编组请求JSON串,及解析响应JSON串。兼容所有ES版本。
Java High Level REST Client: 高级别的REST客户端,基于低级别的REST客户端,增加了编组请求JSON串、解析响应JSON串等相关api。使用的版本需要保持和ES服务端的版本一致,否则会有版本问题。

官方推荐使用高级版,低级版需要自己准确记住api。

2. Java Low Level REST Client 说明

特点,maven 引入、使用介绍: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-low.html

API doc :https://artifacts.elastic.co/javadoc/org/elasticsearch/client/elasticsearch-rest-client/6.2.4/index.html.

3. Java High Level REST Client 说明

从6.0.0开始加入的,目的是以java面向对象的方式来进行请求、响应处理。
每个API 支持 同步/异步 两种方式,同步方法直接返回一个结果对象。异步的方法以async为后缀,通过listener参数来通知结果。
高级java REST 客户端依赖Elasticsearch core project

兼容性说明:

依赖 java1.8 和 Elasticsearch core project
请使用与服务端ES版本一致的客户端版本

springboot集成

  1. 创建springboot项目,在pom.xml文件里面加依赖
		
    		org.elasticsearch
    		elasticsearch
    		7.2.0
		
		
    		org.elasticsearch.client
    		elasticsearch-rest-high-level-client
    		7.2.0
		
  1. application.yml里面配置elasticsearch信息
server:
  port: 8081
  servlet:
    context-path: /es

elasticsearch: 
  ip: 127.0.0.1:9200
  1. 创建ElasticsearchRestClient类
@Configuration
public class ElasticsearchRestClient
{
    private static final int ADDRESS_LENGTH = 2;
    private static final String HTTP_SCHEME = "http";
    
    @Value("${elasticsearch.ip}")
    String[] ipAddress;
    
    @Bean
    public RestClientBuilder restClientBuilder() {
        System.err.println(ipAddress);
        HttpHost[] hosts = Arrays.stream(ipAddress)
                .map(this::makeHttpHost)
                .filter(Objects::nonNull)
                .toArray(HttpHost[]::new);
        return RestClient.builder(hosts);
    }

    @Bean(name = "highLevelClient")
    public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
       //TODO 此处可以进行其它操作
        return new RestHighLevelClient(restClientBuilder);
    }

    
    private HttpHost makeHttpHost(String s) {
        assert StringUtils.isNotEmpty(s);
        String[] address = s.split(":");
        if (address.length == ADDRESS_LENGTH) {
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            System.err.println(ip+"+"+port);
            return new HttpHost(ip, port, HTTP_SCHEME);
        } else {
            return null;
        }
    }

}
  1. 创建索引
try
        {
            Map properties = new HashMap();
            Map propertie = new HashMap();
            propertie.put("type", "text"); // 类型
            // propertie.put("index",true);
            propertie.put("analyzer", "ik_max_word"); // 分词器
            properties.put("title", propertie);
            
            XContentBuilder builder = XContentFactory.jsonBuilder();
            builder.startObject()
                .startObject("mappings")
                .startObject("_doc")
                .field("properties", properties)
                .endObject()
                .endObject()
                .startObject("settings")
                .field("number_of_shards", 3)
                .field("number_of_replicas", 1)
                .endObject()
                .endObject();
            
            CreateIndexRequest request = new CreateIndexRequest("demo").source(builder);
            highLevelClient.indices().create(request, RequestOptions.DEFAULT);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  1. 插入文档
try
        {
            XContentBuilder builder = XContentFactory.jsonBuilder();
            builder.startObject();
            builder.field("title", "我是一条测试文档数据");
            builder.endObject();
            
            IndexRequest request = new IndexRequest("demo").source(builder);
            highLevelClient.index(request, RequestOptions.DEFAULT);
            
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  1. 查询文档
Integer pageIndex = 1;
        Integer pageSize = 5;
        String indexName = "demo";
        Map data = new HashMap<>();
        data.put("title", title); 
        
        List> result = new ArrayList>();
        SearchRequest searchRequest = new SearchRequest(indexName);
        // searchRequest.types(indexName);
        queryBuilder(pageIndex, pageSize, data, indexName, searchRequest);
        try
        {
            SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits())
            {
                Map map = hit.getSourceAsMap();
                map.put("id", hit.getId());
                result.add(map);
                
                // 取高亮结果
                Map highlightFields = hit.getHighlightFields();
                HighlightField highlight = highlightFields.get("title");
                Text[] fragments = highlight.fragments(); // 多值的字段会有多个值
                String fragmentString = fragments[0].string();
                System.out.println("高亮:" + fragmentString);
            }
            System.out.println("pageIndex:" + pageIndex);
            System.out.println("pageSize:" + pageSize);
            System.out.println(response.getHits().getTotalHits());
            System.out.println(result.size());
            for (Map map : result)
            {
                System.out.println(map.get("title"));
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

private void queryBuilder(Integer pageIndex, Integer pageSize, Map query, String indexName,
        SearchRequest searchRequest)
    {
        if (query != null && !query.keySet().isEmpty())
        {
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            if (pageIndex != null && pageSize != null)
            {
                searchSourceBuilder.size(pageSize);
                if (pageIndex <= 0)
                {
                    pageIndex = 0;
                }
                searchSourceBuilder.from((pageIndex - 1) * pageSize);
            }
            BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
            query.keySet().forEach(key -> {
                boolBuilder.must(QueryBuilders.matchQuery(key, query.get(key)));
                
            });
            searchSourceBuilder.query(boolBuilder);
            
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("title").preTags("").postTags("");
            highlightTitle.highlighterType("unified");
            highlightBuilder.field(highlightTitle);
            searchSourceBuilder.highlighter(highlightBuilder);
            
            searchRequest.source(searchSourceBuilder);
        }
    }

总结

elasticsearch的java api操作有很多例如聚合操作等,可以参考相关文档学习。这些东西看起来很简单,却很费时间。网上的资料参差不齐,用得elasticsearch版本方式也不尽相同,官网文档有事英文的,真让人头大

项目源码:https://download.csdn.net/download/pyq666/11560678

你可能感兴趣的:(ElasticSearch)