使用 Elasticsearch RestHighLevelClient 查询 Elasticsearch

pom:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.8
        
    
    com.spring
    elasticsearch-high-level-rest
    0.0.1-SNAPSHOT
    elasticsearch-high-level-rest
    elasticsearch-high-level-rest
    
        1.8
        7.1.0
        2.0.30
    
    
        
            org.springframework.boot
            spring-boot-starter
        
        
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
            
                
                    org.springframework.data
                    spring-data-elasticsearch
                
            
        
        
        
        
            org.elasticsearch.client
            elasticsearch-rest-client
            ${elasticsearch.version}
        
        
        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            ${elasticsearch.version}
            
                
                    org.elasticsearch
                    elasticsearch
                
            
        
        
        
            org.elasticsearch
            elasticsearch
            ${elasticsearch.version}
        
        
        
            org.projectlombok
            lombok
            true
        
        
            com.alibaba
            fastjson
            ${fastjson.version}
        
        
            junit
            junit
            test
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    


代码:

package com.spring.elasticsearch;

import com.alibaba.fastjson.JSON;
import com.spring.elasticsearch.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ElasticsearchHighLevelRestApplicationTests {
    
    @Autowired
    private RestClient restClient;
    
    @Autowired
    private RestHighLevelClient highLevelClient;
    
    /**
     * high-rest Client测试类
     * 

* 说明:通过SearchRequest、SearchSourceBuilder、QueryBuilders构建请求,API封装的更丰富 */ @Test public void highRestClientQueryTest() { String indice = "products*"; SearchRequest searchRequest = new SearchRequest(indice); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchAllQuery()); sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); log.info("ES查询DSL语句:\n GET {} \n {}", String.format("/%s/_search", searchRequest.indices()[0]), sourceBuilder); searchRequest.source(sourceBuilder); try { SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT); Arrays.stream(response.getHits().getHits()).forEach(i -> { //索引名称 log.info(i.getIndex()); log.info(i.getSourceAsString()); }); long hits = response.getHits().getTotalHits().value; log.info("记录总数:" + response.getHits().getTotalHits().value); Assert.assertEquals(0L, hits); } catch (Exception e) { log.error("highRestClientTest fail", e); } } @Test public void highRestClientCreateIndexTest() throws IOException { String indice = "products"; DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indice); highLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); // 创建名称为products的索引 CreateIndexRequest productsIndex = new CreateIndexRequest(indice); //配置 settings,分片、副本等信息 productsIndex.settings(Settings.builder().put("index.number_of_shards", 5).put("index.number_of_replicas", 1)); //配置字段类型。字段类型可以通过 JSON 字符串、Map 以及 XContentBuilder 三种方式来构建 // JSON 方式 // productsIndex.mapping("{'properties': {'title': {'type': 'text'}}}", XContentType.JSON); //Map 方式 Map productName = new HashMap<>(); productName.put("type", "text"); productName.put("analyzer","ik_max_word"); Map desc = new HashMap<>(); desc.put("type", "text"); desc.put("analyzer","ik_max_word"); Map properties = new HashMap<>(); properties.put("productname", productName); properties.put("desc", desc); Map mappings = new HashMap<>(); mappings.put("properties", properties); productsIndex.mapping(mappings); //执行请求,创建索引 CreateIndexResponse result = highLevelClient.indices().create(productsIndex, RequestOptions.DEFAULT); Assert.assertNotNull(result); } @Test public void highRestClientBulkInsertTest() throws IOException { // 单条数据插入也可以用 Bulk String indice = "products"; String type = "_doc"; // List> list = new ArrayList<>(); ArrayList list = new ArrayList<>(); list.add(new ProductVo("优必选阿尔法智能机器人alpha1p编程学习教育人形春晚跳舞机器人", "迎接变化的世界,阿尔法机器人成为世界上广泛应用的仿人智能机器人,正在悄悄改变你的世界;整体采用一体成型材料,凸显简洁优雅之感;整体采用安全材质,实现零污染!")); list.add(new ProductVo("安瑞井女装春秋季新款休闲外套原创中长款撞色品牌logo运动风外套", "外套精选优质的聚酯纤维材质制作,触感极佳,且有着良好的透气性和排湿性。它的外形简洁利落,线条流畅,显得更加时髦有个性。")); if (CollectionUtils.isEmpty(list)) { return; } int size = list.size(); BulkRequest request = new BulkRequest(); for (int i = 0; i < size; i++) { // 批量添加。批量更新也是类似 request.add(new IndexRequest(indice, type).source(JSON.toJSONString(list.get(i)), XContentType.JSON)); } BulkResponse result = highLevelClient.bulk(request, RequestOptions.DEFAULT); Assert.assertNotNull(result); } @Test public void highRestClientSearchTest() throws IOException { String indice = "products"; SearchRequest searchRequest = new SearchRequest(indice); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 添加 match_all 查询 // searchSourceBuilder.query(QueryBuilders.matchAllQuery()); searchSourceBuilder.query(QueryBuilders.termQuery("productname", "机器人")); // searchSourceBuilder.query(QueryBuilders.matchPhraseQuery("productname", "人")); // searchSourceBuilder.query(QueryBuilders.queryStringQuery("外")); // searchSourceBuilder.query(QueryBuilders.fuzzyQuery("productname","外")); log.info("ES查询DSL语句:\nGET {}\n{}", String.format("/%s/_search", searchRequest.indices()[0]), searchSourceBuilder); // 将 SearchSourceBuilder 添加到 SeachRequest 中 searchRequest.source(searchSourceBuilder); SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT); long hitsCount = response.getHits().getTotalHits().value; Assert.assertTrue(hitsCount > 0); SearchHit[] searchHits = response.getHits().getHits(); List productVoList = new ArrayList<>(); Arrays.stream(searchHits).forEach(i -> { //索引名称 /*log.info(i.getIndex()); log.info(i.getSourceAsString());*/ ProductVo productVo = JSON.parseObject(i.getSourceAsString(), ProductVo.class); productVoList.add(productVo); }); log.info(productVoList.get(0).getProductName()); Assert.assertNotNull(productVoList.get(0).getProductName()); } @Test public void highRestClientBulkUpdateTest() throws IOException { // 单条数据插入也可以用 Bulk String indice = "products"; String type = "_doc"; // List> list = new ArrayList<>(); int size = 1; BulkRequest request = new BulkRequest(); for (int i = 0; i < size; i++) { // 批量添加。批量更新也是类似 UpdateRequest updateRequest = new UpdateRequest(indice, type).id("Sx5Qc4oB9GLeuiYl1ZOP") .doc(XContentType.JSON, "productname", "安瑞井女装春秋季新款休闲外套原创中长款撞色品牌logo运动风外套"); request.add(updateRequest); } BulkResponse result = highLevelClient.bulk(request, RequestOptions.DEFAULT); Assert.assertNotNull(result); } }

你可能感兴趣的:(elasticsearch,大数据,搜索引擎)