springboot使用ES查询

2023-12-30 19:27:33
第一步:导入依赖
        <!--es缓存依赖-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

第二步:创建文档需要的实体类

package com.example.demousermanagement.beans;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Products {
    private String id;
    private String type;
    private String name;
    private String desc;
}

第三步:测试---创建索引、用分词器创建索引、添加单个文档、添加多个文档、查询


@Slf4j
@SpringBootTest
class DemoUserManagementApplicationTests {

    //声明es客户端
    private RestHighLevelClient highLevelClient;

    public RestHighLevelClient restClient() {
        log.info("Elasticsearch init start ......");
        RestHighLevelClient restClient = null;
        try {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials("elastic", "123456MQL"));

            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslContext, NoopHostnameVerifier.INSTANCE);
            restClient = new RestHighLevelClient(
                    RestClient.builder(
                                    new HttpHost("localhost", 9200, "https"))
                            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                                    httpClientBuilder.disableAuthCaching();
                                    httpClientBuilder.setSSLStrategy(sessionStrategy);
                                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                                    return httpClientBuilder;
                                }
                            }));
        } catch (Exception e) {
            log.error("elasticsearch TransportClient create error!!", e);
        }
        return restClient;
    }

    @BeforeEach
    void setUp(){
        //初始化客户端
        highLevelClient = restClient();
    }

    @AfterEach
    void tearDown() throws IOException {
        highLevelClient.close();
    }

    @Test
    void addIndex() throws IOException {
        //创建索引--相当于数据库
        CreateIndexRequest request = new CreateIndexRequest("products");
        final CreateIndexResponse createIndexResponse = highLevelClient.indices().create(request, RequestOptions.DEFAULT);
        log.info(createIndexResponse.toString());
    }

    /**
     * 使用ik分词器创建索引--相当于数据库
     */
    @Test
    public void testIK() throws IOException {

        String source = "{\n" +
                "\t\"mappings\": {\n" +
                "\t\t\"properties\": {\n" +
                "\t\t\t\"desc\": {\n" +
                "\t\t\t\t\"type\": \"text\",\n" +
                "\t\t\t\t\"fields\": {\n" +
                "\t\t\t\t\t\"keyword\": {\n" +
                "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
                "\t\t\t\t\t\t\"ignore_above\": 256\n" +
                "\t\t\t\t\t}\n" +
                "\t\t\t\t}\n" +
                "\t\t\t},\n" +
                "\t\t\t\"id\": {\n" +
                "\t\t\t\t\"type\": \"long\"\n" +
                "\t\t\t},\n" +
                "\t\t\t\"name\": {\n" +
                "\t\t\t\t\"type\": \"text\",\n" +
                "\t\t\t\t\"fields\": {\n" +
                "\t\t\t\t\t\"keyword\": {\n" +
                "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
                "\t\t\t\t\t\t\"ignore_above\": 256\n" +
                "\t\t\t\t\t}\n" +
                "\t\t\t\t}\n" +
                "\t\t\t},\n" +
                "\t\t\t\"type\": {\n" +
                "\t\t\t\t\"type\": \"text\",\n" +
                "\t\t\t\t\"fields\": {\n" +
                "\t\t\t\t\t\"keyword\": {\n" +
                "\t\t\t\t\t\t\"type\": \"keyword\",\n" +
                "\t\t\t\t\t\t\"ignore_above\": 256\n" +
                "\t\t\t\t\t}\n" +
                "\t\t\t\t}\n" +
                "\t\t\t}\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";

        //创建索引
        CreateIndexRequest request = new CreateIndexRequest("products");

        //给请求对象设置参数
        request.source(source, XContentType.JSON);

        final CreateIndexResponse createIndexResponse = highLevelClient.indices().create(request, RequestOptions.DEFAULT);
        log.info(createIndexResponse.toString());
    }

    /**
     * 创建文档--相当于添加单条表记录
     */
    @Test
    public void testDoc() throws IOException {
        try {
            IndexRequest request = new IndexRequest("products").id("9");
            String json = "{\n" +
                    "\t\"name\": \"pear32\",\n" +
                    "\t\"type\": \"9fruit9\",\n" +
                    "\t\"desc\": \"good foot pear32\"\n" +
                    "}";
            request.source(json, XContentType.JSON);
            final IndexResponse index = highLevelClient.index(request, RequestOptions.DEFAULT);
            log.info(index.toString());
        } catch (Exception e) {
            String msg = e.getMessage();
            if (!msg.contains("201 Created") && !msg.contains("200 OK")) {
                throw e;
            }
        }
    }

    /**
     * 批量添加文档--相当于批量添加表记录
     */
    @Test
    public void testBulk() throws IOException {
        try{
            List<Products> list = new ArrayList<>();
            list.add(new Products("3", "aaa", "bbb", "ccc"));
            list.add(new Products("4", "eee", "fff", "ggg"));
            list.add(new Products("5", "hhh", "ggg", "kkk"));

            //创建批量请求对象
            BulkRequest bulk = new BulkRequest();
            for (Products products : list) {
                IndexRequest request = new IndexRequest("products").id(products.getId());
                String json = JSON.toJSONString(products);
                request.source(json, XContentType.JSON);
                bulk.add(request);
            }
            highLevelClient.bulk(bulk, RequestOptions.DEFAULT);
        }catch (Exception e){
            String msg = e.getMessage();
            if (!msg.contains("201 Created") && !msg.contains("200 OK")) {
                throw e;
            }
        }
    }

    /**
     * 根据id查询文档
     */
    @Test
    public void testQueryDocById() throws IOException {

        GetRequest request = new GetRequest("products", "3");
        GetResponse documentFields = highLevelClient.get(request, RequestOptions.DEFAULT);
        String sourceAsString = documentFields.getSourceAsString();
        log.info("----" + sourceAsString);
    }

    /**
     * 跟俊其他条件查询
     */
    @Test
    public void testQueryDocByConditions() throws IOException {
        //获取条件对象
        SearchRequest request = new SearchRequest("products");
        //设置文档查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.termQuery("type", "aaa"));
        request.source(builder);

        //执行查询
        SearchResponse response = highLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Products products = JSON.parseObject(sourceAsString, Products.class);
            log.info(products.toString());
        }

    }


}


文章来源:https://blog.csdn.net/qianlima210210/article/details/135308440
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。