SpringBoot整合ElasticSearch7.16.3

SpringBoot整合ElasticSearch7.16.3

ElasticSearch7.15.x版本后,废弃了高级Rest客户端的功能,转为JavaAPI客户端,以下来源ElasticSearch官网

The Elasticsearch Java API Client is an entirely new client library that has no relation to the older High Level Rest Client (HLRC). This was a deliberate choice to provide a library that is independent from the Elasticsearch server code and that provides a very consistent and easier to use API for all Elasticsearch features.
From https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/migrate-hlrc.html

maven引入

		<dependency>
            <groupId>co.elastic.clientsgroupId>
            <artifactId>elasticsearch-javaartifactId>
            <version>7.16.3version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.12.3version>
        dependency>
        <dependency>
            <groupId>jakarta.jsongroupId>
            <artifactId>jakarta.json-apiartifactId>
            <version>2.0.1version>
        dependency>

简单API

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

/**
 * @author qingyi
 * @date 2022-02-10 15:07
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private String name;

    private String price;

    private String imgPath;
}

配置

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author qingyi
 * @date 2022-02- 17:59
 **/
 @Configuration
public class ElasticSearchConfig {

    @Bean
    public ElasticsearchClient elasticsearchClient() {
    	//对应ElasticSearch的IP端口
        RestClient restClient = RestClient.builder(new HttpHost("xx.xx.xx.xx",9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);

		// es设置了密码,可以这样连接
		/* 
		CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("账号", "密码"));
        RestClient restClient = RestClient.builder(new HttpHost("xx.xx.xx.xx",9200)).setHttpClientConfigCallback(httpAsyncClientBuilder -> {
            httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpAsyncClientBuilder;
        }).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport); 
        */
    }
}

索引

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.KeywordProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TextProperty;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
class ElasticsearchDemoApplicationTests {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    //对应的kibana语句
    /*
    PUT /book
    {
        "mappings": {
        "properties": {
            "name":{
                "type": "text",
                "analyzer": "ik_max_word",
                "search_analyzer": "ik_smart"
            },
            "price":{
                "type": "keyword"
            },
            "imgPath":{
                "type": "keyword"
            }
        }
    }
    }
    */
    // 创建索引
    @Test
    void createIndex() throws IOException {

        // 配置索引
        Map<String, Property> property = new HashMap<>();
        /*

            分析器主要有两种情况会被使用:
                第一种是插入文档时,将text类型的字段做分词然后插入倒排索引,
                第二种就是在查询时,先对要查询的text类型的输入做分词,再去倒排索引搜索
            analyzer: 分词器
            searchAnalyzer: 查询分词器
         */
        property.put("name", new Property(new TextProperty.Builder().analyzer("ik_max_word").searchAnalyzer("ik_smart").index(true).store(true).build()));
        property.put("price", new Property(new KeywordProperty.Builder().index(true).store(true).build()));
        property.put("imgPath", new Property(new KeywordProperty.Builder().index(true).store(true).build()));

        TypeMapping typeMapping = new TypeMapping.Builder().properties(property).build();

        /*
            索引设置:
            numberOfReplicas:是数据分片数,默认为5,有时候设置为3
            numberOfReplicas 是数据备份数,如果只有一台机器,设置为0
         */
        IndexSettings indexSettings = new IndexSettings.Builder().numberOfReplicas("5").build();

        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                .index("book")
                .aliases("b1", new Alias.Builder().isWriteIndex(true).build())
                .mappings(typeMapping)
                .settings(indexSettings)
                .build();

        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(createIndexRequest);
        System.out.println(createIndexResponse.acknowledged());
    }

    //测试判断是否拥有某个索引
    @Test
    void existsIndex() throws IOException {
        //创建获取索引请求
        ExistsRequest existsRequest = new ExistsRequest.Builder().index("b2").build();
        //执行获取索引请求判断是否有这个索引
        BooleanResponse booleanResponse = elasticsearchClient.indices().exists(existsRequest);
        System.out.println(booleanResponse.value());
    }

    //获取索引信息
    @Test
    void getIndex() throws IOException {
        //创建获取索引请求
        GetIndexRequest getIndexRequest = new GetIndexRequest.Builder().index("book").build();
        //执行获取索引请求判断是否有这个索引
        GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(getIndexRequest);
        System.out.println(getIndexResponse.result());
    }

    //DELETE /book
    // 删除索引
    @Test
    void deleteIndex() throws IOException {
        //创建删除索引请求
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index("book").build();
        //执行
        DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(deleteIndexRequest);
        System.out.println(deleteIndexResponse.acknowledged());
    }

}

文档

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.ye.elasticsearchdemo.pojo.Book;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author qingyi
 * @date 2022-02-10 15:06
 **/
@SpringBootTest
public class DocTests {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    // kibana语句
    /*
    PUT /book/_doc/1
    {
        "name":"高性能Mysql",
        "price":"81.32",
        "imgPath":"https://img30.360buyimg.com/vc/jfs/t24145/294/1264419103/700620/6d764088/5b580f1eN305e28c1.jpg"
    }
    */
    //创建文档
    @Test
    void createDocument() throws IOException {
        // 创建对象
        Book book = new Book("高性能Mysql", "81.32", "https://img30.360buyimg.com/vc/jfs/t24145/294/1264419103/700620/6d764088/5b580f1eN305e28c1.jpg");
        // 创建添加文档的请求
        IndexRequest<Book> indexRequest = new IndexRequest.Builder<Book>().index("book").document(book).id("1").build();

        // 执行
        IndexResponse indexResponse = elasticsearchClient.index(indexRequest);

        System.out.println(indexResponse.toString());//返回索引信息
        System.out.println(indexResponse.result());//返回id
    }

    //查看是否存在
    @Test
    void existsDocument() throws IOException {
        GetRequest getRequest = new GetRequest.Builder().index("book").id("1").build();
        GetResponse<Book> bookGetResponse = elasticsearchClient.get(getRequest, Book.class);
        //查看是否存在
        System.out.println(bookGetResponse.found());
    }


    //DELETE /book/_doc/1
    //删除文档信息
    @Test
    void deleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest.Builder().index("book").id("1").build();
        DeleteResponse delete = elasticsearchClient.delete(deleteRequest);
        System.out.println(delete.result());//删除状态
        System.out.println(delete.toString());//删除信息
    }

    /**
     * 获取文档
     * @throws IOException
     */
    @Test
    void getDocument() throws IOException {
        // get /index/_doc/1
        GetRequest getRequest = new GetRequest.Builder().index("book").id("1").build();
        GetResponse<Book> bookGetResponse = elasticsearchClient.get(getRequest, Book.class);

        Book book = bookGetResponse.source();
        System.out.println("book = " + book);
    }

    /**
     * 分页获取文档
     */
    @Test
    void getDocumentByPage() throws IOException {
        SearchRequest searchRequest = new SearchRequest.Builder().index("book").from(0).size(10).build();
        SearchResponse<Book> bookSearchResponse = elasticsearchClient.search(searchRequest, Book.class);

        List<Hit<Book>> bookList = bookSearchResponse.hits().hits();
        bookList.forEach(item->System.out.println(item.source()));
    }

	/**
	 * 更新文档
	 */
    @Test
    void updateDocument() throws IOException {
        Book book = new Book();
        book.setName("算法指南");

        UpdateRequest<Book, Book> bookBookUpdateRequest = new UpdateRequest.Builder<Book, Book>().index("book").id("1").doc(book).build();

        UpdateResponse<Book> personUpdateResponse = elasticsearchClient.update(bookBookUpdateRequest, Book.class);

        // 执行结果
        System.out.println(personUpdateResponse.result());
    }
}

你可能感兴趣的:(ElasticSearch,spring,boot,elasticsearch)