> Java > java지도 시간 > springboot에 elasticsearch를 통합하는 방법

springboot에 elasticsearch를 통합하는 방법

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2023-06-01 08:22:36
앞으로
1410명이 탐색했습니다.

1. 종속성 소개

1

2

3

4

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>

</dependency>

로그인 후 복사

2. 쓰기 엔터티 매핑 클래스

1

2

3

4

5

6

7

8

9

@Data

@Document(indexName = "index", createIndex = true)

public class Index {

    @Id

    private String id;

 

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")

    private String content;

}

로그인 후 복사

3. 쓰기 액세스 인터페이스(인덱스를 자동으로 생성해야 하는 경우 이 인터페이스를 작성해야 합니다. 그렇지 않으면 프로젝트에서 인덱스를 자동으로 감지하고 생성하지 않습니다.) 시작됩니다)

1

2

3

4

@Repository

public interface IndexRepository extends ElasticsearchRepository<Index, String> {

    Page<Index> findByContent(String content, Pageable page);

}

로그인 후 복사

4, 테스트, 템플릿 및 저장소를 사용하여 테스트

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

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

@SpringBootTest

public class EsTest {

    @Autowired

    ElasticsearchRestTemplate esTemplate;

    @Autowired

    IndexRepository indexRepository;

     

    @BeforeEach

    public void init() {

        System.out.println("init");

        indexRepository.deleteAll();

        indexRepository.saveAll(ListUtil.of(

        new Index("1","美国留给伊拉克的是个烂摊子吗"),

        new Index("2","公安部:各地校车将享最高路权"),

        new Index("3","中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"),

        new Index("4","中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"),

        new Index("5","中国天眼向全球正式开放下月世界大赛将比拼FAST脉冲星搜索")

        ));

    }

     

    @Test

    void testRepositoryQuery() {

        Page<Index> pageList = indexRepository.findByContent("中国", PageRequest.of(0, 10));

        pageList.getContent().forEach(e -> {

            System.out.println("repositoryQuery => "+e);

        });

    }

     

    @Test

    void testTemplateQuery() {

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()

                .must(QueryBuilders.simpleQueryStringQuery("中国").field("content"));

        NativeSearchQuery query = new NativeSearchQueryBuilder()

                .withQuery(queryBuilder)

                .withPageable(PageRequest.of(0, 10))

                .build();

        SearchHits<Index> search = esTemplate.search(query, Index.class);

        if(search.hasSearchHits()) {

            search.getSearchHits().forEach(e -> {

                System.out.println("templateQuery => "+e.getContent());

            });

        }

    }

}

로그인 후 복사

1

2

3

4

5

6

7

8

init data

templateQuery => Index(id=3, content=中韩渔警冲突调查:韩警平均每天扣1艘中国渔船)

templateQuery => Index(id=4, content=中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首)

templateQuery => Index(id=5, content=中国天眼向全球正式开放下月世界大赛将比拼FAST脉冲星搜索)

init data

repositoryQuery => Index(id=3, content=中韩渔警冲突调查:韩警平均每天扣1艘中国渔船)

repositoryQuery => Index(id=4, content=中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首)

repositoryQuery => Index(id=5, content=中国天眼向全球正式开放下月世界大赛将比拼FAST脉冲星搜索)

로그인 후 복사

5, 예약된 작업을 시작하고 정기적으로 핑하여 연결 시간 초과를 방지할 수 있습니다

1

2

3

4

    @Scheduled(fixedRate = 15000)

    public void ping() {

        esTemplate.execute(client -> client.ping(RequestOptions.DEFAULT));

    }

로그인 후 복사

위 내용은 springboot에 elasticsearch를 통합하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿