使用 Elasticsearch RestHighLevelClient 查询 Elasticsearch

pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.8</version>
        <relativePath/>
    </parent>
    <groupId>com.spring</groupId>
    <artifactId>elasticsearch-high-level-rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch-high-level-rest</name>
    <description>elasticsearch-high-level-rest</description>
    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.1.0</elasticsearch.version>
        <fastjson.version>2.0.30</fastjson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        
        <!-- elasticsearch的starter, 主要是为了实现自动化配置,方便快捷的获取 rest client -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.data</groupId>
                    <artifactId>spring-data-elasticsearch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
        <!-- low-level client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        
        <!-- high-level client ,默认依赖的elasticsearch存在版本差异,排除后添加统一的es版本-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 使用low-level client不需要,但是high-level client需要依赖-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

代码:

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测试类
     * <p>
     * 说明:通过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<String, String> productName = new HashMap<>();
        productName.put("type", "text");
        productName.put("analyzer","ik_max_word");
        
        Map<String, String> desc = new HashMap<>();
        desc.put("type", "text");
        desc.put("analyzer","ik_max_word");
        
        Map<String, Object> properties = new HashMap<>();
        properties.put("productname", productName);
        properties.put("desc", desc);
        
        Map<String, Object> 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<Map<String, Object>> list = new ArrayList<>();
        
        ArrayList<ProductVo> 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<ProductVo> 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<Map<String, Object>> 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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值