springboot simple (13) springboot Elasticsearch(Elasticsearch8.5.1)

Here first briefly introduces Elasticsearch, and then implements springboot integrated Elasticsearch.

Versions:
Elasticsearch: v8.5.1
Kibana: v8.5.1

There are two ways to integrate elasticsearch with springboot.
1) Rest client RestHingLevelClient;
2) Interface ElasticSearchRepository.
The first method is used here.

1 Introduction to Elasticsearch

ElasticSearch is an open source search engine based on Apache Lucene.
Kibana is an open source analytics and visualization platform designed to visually manipulate Elasticsearch.

That is to say :
ElasticSearch is just a background program without an interface;
Kibana is the front end corresponding to ElasticSearch.

Key terms:

  • Index (Index)
    An index is a collection of documents with some similar characteristics. For example, customer data index, product catalog index, and order data index.
  • Document (document)
    document is the basic unit that can be indexed. Documents are represented using JSON.

2 springboot integrated Elasticsearch

Elasticsearch already supports Index (index), Document (document), Graph (graph), Machine learning (machine learning), etc.
insert image description here
Here we introduce the simple use of Index (index) and Document (document).

Step 1: Introduce dependent packages in pom:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
			<version>3.0.2</version>
		</dependency>

Step 2: application.properties set related parameters:

server.port =8081

spring.data.elasticsearch.repositories.enabled = true
spring.data.elasticsearch.cluster-nodes = localhost:9300

spring.elasticsearch.rest.username=elastic
spring.elasticsearch.rest.password=123456
spring.elasticsearch.rest.uris=localhost:9200

Step 3: The corresponding configuration class ElasticSearchConfig.java:

@Component
@Configuration
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {
    
    
    @Value("${spring.elasticsearch.rest.uris}")
    private String uris ;
    @Value("${spring.elasticsearch.rest.username}")
    private String username;
    @Value("${spring.elasticsearch.rest.password}")
    private String password ;

    @Override
    @Bean(destroyMethod = "close")
    public RestHighLevelClient elasticsearchClient() {
    
    
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(uris)
                .withBasicAuth(username, password)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

Step 4: Implement index tool class IndexUtil.java:

@Component
public class IndexUtil {
    
    
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引index
     * @param index
     * @return
     * @throws IOException
     */
    public boolean createIndex(String index){
    
    
        if (!isIndexExist(index)) {
    
    
            return false;
        }
        boolean isAcknowledged = false;
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        try {
    
    
            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            isAcknowledged = acknowledgedResponse.isAcknowledged();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            return isAcknowledged;
        }
    }

    /**
     * 删除索引
     * @param index
     * @return
     * @throws IOException
     */
    public boolean deleteIndex(String index){
    
    
        if (!isIndexExist(index)) {
    
    
            return false;
        }
        boolean isAcknowledged = false;
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        try {
    
    
            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
            isAcknowledged = acknowledgedResponse.isAcknowledged();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            return isAcknowledged;
        }
    }

    /**
     * 判断索引是否存在
     * @param index
     * @return
     * @throws IOException
     */
    public boolean isIndexExist(String index) {
    
    
        boolean isExist = false;
        try {
    
    
            GetIndexRequest getIndexRequest = new GetIndexRequest(index);
            isExist = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            return isExist;
        }
    }
}

Step 5: Implement document tool class DocumentUtil.java:

@Component
public class DocumentUtil {
    
    
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 添加document
     * @param object
     * @param index
     * @param id
     * @return
     */
    public void addDocument(Object object, String index,String id){
    
    
        //1 create IndexRequest
        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.id(id);
        indexRequest.timeout(TimeValue.timeValueSeconds(1));
        String content = JSON.toJSONString(object);
        indexRequest.source(content, XContentType.JSON);
        try {
    
    
            //2 send IndexRequest
            IndexResponse indexResponse =restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 添加document,随机id
     * @param object
     * @param index
     * @return
     */
    public void addDocument(Object object, String index){
    
    
        String id= "";
        id = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
        addDocument(object, index, id);
    }

    /**
     * get Document
     * @param index
     * @param id
     * @return
     */
    public GetResponse getDocumnet(String index,String id){
    
    
        GetResponse getResponse = null;
        GetRequest getRequest = new GetRequest(index, id);
        try {
    
    
            getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        }catch (IOException e){
    
    
            e.printStackTrace();
        } finally {
    
    
            return  getResponse;
        }
    }

    /**
     * update document
     * @param object
     * @param index
     * @param id
     */
    public void updateDocument(Object object, String index,String id){
    
    
        //1 create UpdateRequest
        UpdateRequest updateRequest = new UpdateRequest(index,id);
        updateRequest.timeout(TimeValue.timeValueSeconds(1));
        String content = JSON.toJSONString(object);
        updateRequest.doc(content, XContentType.JSON);
        try {
    
    
            //2 send UpdateRequest
            UpdateResponse updateResponse =restHighLevelClient.update(updateRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 删除Document
     * @param index
     * @param id
     */
    public void deleteDocument(String index,String id){
    
    
        //1 create DeleteRequest
        DeleteRequest deleteRequest = new DeleteRequest(index, id);
        try {
    
    
            //2 send DeleteRequest
            DeleteResponse deleteResponse =  restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    public SearchResponse search(String index, TermQueryBuilder termQueryBuilder){
    
    
        //1 create SearchRequest
        SearchRequest searchRequest = new SearchRequest(index);

        //2 create SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));

        //3 查询条件放入SearchRequest
        searchRequest.source(searchSourceBuilder);

        //4 send SearchRequest
        SearchResponse searchResponse = null;
        try {
    
    
            searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            return searchResponse;
        }
    }

    public SearchResponse searchHighLight(String index, TermQueryBuilder termQueryBuilder){
    
    
        //1 create SearchRequest
        SearchRequest searchRequest = new SearchRequest(index);

        //2 create SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.highlighter();
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));

        //3 查询条件放入SearchRequest
        searchRequest.source(searchSourceBuilder);

        //4 send SearchRequest
        SearchResponse searchResponse = null;
        try {
    
    
            searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            return searchResponse;
        }
    }
}

3 Test verification

Prerequisite: Install and run ElasticSearch and Kibana.

Step 1: create index, postman sends request:
insert image description here

Then, enter in Kibana:
GET /_cat/indices?v
query to create the index successfully. insert image description here
Step 2: Create a Document, and postman sends a request:
insert image description here
Then, enter in Kibana:
GET heroic/_doc/1
query to find that the Document is created successfully. insert image description here
Step 3: Query Document, postman sends a request:
insert image description here

Step 4: Modify the Document, change the name "Guan Yu" to "Liu Bei";
Postman sends a request:
insert image description here
Then, enter in Kibana:
GET heroic/_doc/1
query to find that the Document has been modified successfully.
insert image description here
Step 5: Delete the Document, postman sends a request:
insert image description here
Then, enter in Kibana:
GET heroic/_doc/1
query to find that the Document is deleted successfully.
insert image description here
See the code for details:
https://gitee.com/linghufeixia/springboot-simple
chapter9-1


教程列表
springboot simple(0) springboot简介
springboot simple(1) springboot Helloworld
springboot simple(2) springboot Starter
springboot simple(3 )springboot Web开发
springboot simple(4)springboot 数据持久化
springboot simple (5) springboot Nosql
springboot simple (6) springboot mqtt
springboot simple (7) springboot thrift
springboot simple (8) springboot kafka
springboot simple (9) springboot jpa(Hibernate)
springboot simple (10) springboot protobuf
springboot simple (11) springboot protostuff
springboot simple (12) springboot RabbitMQ
springboot simple (13) springboot Elasticsearch

Guess you like

Origin blog.csdn.net/afei8080/article/details/129081165