Featured image of post SpringBoot整合ElasticSearch

SpringBoot整合ElasticSearch

延續上一篇

本文會用到的連結

How to Integrate Elastic Search With Spring Boot CRUD Project| Spring Boot | Elasticsearch| EnggAdda

這東西的坑真的很多

springBoot Elastic Search 還有相關的套件版本必須一致

shit-leslie-jordan-gif

版本設置與Maven

Elastic Search & Kibana 版本

我個人使用的設置如下

Elastic Search: 8.13.2

Kibana:8.13.2

Maven

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>elasticsearch-rest-high-level-client</artifactId>
			<version>7.4.0</version>
			<exclusions>
				<exclusion>
					<artifactId>log4j-api</artifactId>
					<groupId>org.apache.logging.log4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>

SprignBoot版本

SpringBoot:3.2.5

SpringBoot與Elastic連線設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {
    private String host ="localhost";
    private Integer port=9200;

    /**
     * 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(host, port, "http")
                )
        );
    }
}

基本操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ElasticSearchService {
    @Resource
    private RestHighLevelClient client;
    public void test() throws IOException {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        SearchRequest indices = new SearchRequest().indices("news_headlines");
        SearchResponse search = client.search(indices, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits) {
            log.info(hit.getSourceAsString());
        }

    }
}

image-20240429180956639

Licensed under CC BY-NC-SA 4.0