Elasticsearch學習(三)springboot整合ElasticSearch

RenshenLi發表於2021-01-02


前言

本篇主要對介紹springboot2.4.0整合ElasticSearch的步驟,通過springboot簡單的操作ElasticSearch。


提示:以下是本篇文章正文內容,下面案例可供參考

一、整合步驟

1、引入ElasticSearch依賴


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

2、新增配置檔案

在appcation配置檔案中新增es的地址和埠

spring.elasticsearch.rest.uris=http://192.168.32.129:9200

3、建立實體類

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "student", shards = 3, replicas = 2)
public class Student {

    @Id
    private Long id;
    @Field(type = FieldType.Keyword, store = true)
    private String name;
    @Field(type = FieldType.Text, store = true,analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String description;

}

4、建立測試類

注入ElasticsearchRestTemplate,通過ElasticsearchRestTemplate來操作es


@RunWith(SpringRunner.class)
@SpringBootTest(classes = BizApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class StudentTest {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;


}

三、測試

1.建立索引

    @Test
    public void createIndexTest(){

        //刪除舊索引
        IndexOperations indexOperations = restTemplate.indexOps(Student.class);
        if (indexOperations.exists()) {
            indexOperations.delete();
        }
       //建立索引
        boolean create = indexOperations.create();
        Assert.assertTrue(create);
        //建立對映資訊
        boolean putMapping = indexOperations.putMapping();
        Assert.assertTrue(putMapping);


    }

2.新增資料

    @Test
    public void saveDataTest(){
        //存入三條資料
        Student student1 = new Student(1L,"張三","我是一個三好學生");
        Student student2 = new Student(2L,"李四","我是一個愛逃課的學生");
        Student student3 = new Student(3L,"王五","我是一個愛睡覺的學生");
        ImmutableList<Student> students = ImmutableList.of(student1, student2, student3);
        restTemplate.save(students);

    }

3.檢索資料

【1】通過id查詢

查詢條件: id="2

    @Test
    public void searchByIdTest(){

        ConstantScoreQueryBuilder constantScoreQueryBuilder = QueryBuilders.
                constantScoreQuery(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("id", 2L)));
        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(constantScoreQueryBuilder).build();

        SearchHits<Student> searchResult = restTemplate.search(searchQuery, Student.class);

        Assert.assertTrue(searchResult.getTotalHits() == 1L);
        searchResult.getSearchHits().forEach(System.out::println);
    }

結果命中一條

SearchHit{id='2', score=1.0, sortValues=[], content=Student(id=2, name=李四, description=我是一個愛逃課的學生), highlightFields={}}

【2】通過keyword查詢

查詢條件: name=“張三”

   @Test
    public void searchByNameTest(){

        ConstantScoreQueryBuilder constantScoreQueryBuilder = QueryBuilders.
                constantScoreQuery(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("name", "張三")));
        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(constantScoreQueryBuilder).build();

        SearchHits<Student> searchResult = restTemplate.search(searchQuery, Student.class);

        Assert.assertTrue(searchResult.getTotalHits() == 1L);
        searchResult.getSearchHits().forEach(System.out::println);
    }

結果命中一條

SearchHit{id='1', score=1.0, sortValues=[], content=Student(id=1, name=張三, description=我是一個三好學生), highlightFields={}}

【3】通過text查詢

查詢條件: description=“三好”

    @Test
    public void searchByDescTest(){

        ConstantScoreQueryBuilder constantScoreQueryBuilder = QueryBuilders.
                constantScoreQuery(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", "三好")));
        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(constantScoreQueryBuilder).build();

        SearchHits<Student> searchResult = restTemplate.search(searchQuery, Student.class);

        Assert.assertTrue(searchResult.getTotalHits() == 1L);
        searchResult.getSearchHits().forEach(System.out::println);
    }

結果命中一條帶有三好的

SearchHit{id='1', score=1.0, sortValues=[], content=Student(id=1, name=張三, description=我是一個三好學生), highlightFields={}}

【4】通過text多值查詢

查詢條件: description=“三好” 逃課"

    @Test
    public void searchByDescMultiValuesTest() {

        ConstantScoreQueryBuilder constantScoreQueryBuilder = QueryBuilders.
                constantScoreQuery(QueryBuilders
                                .boolQuery()
                                //1、一個termsQuery
                                .should(QueryBuilders.termsQuery("description", "三好", "逃課"))
                                //2、一個multiMatchQuery
//                               .should(QueryBuilders.multiMatchQuery("三好 逃課","description" ))
                                 //3、多個termQuery組合
//                               .should(QueryBuilders.termQuery("description", "三好"))
//                               .should(QueryBuilders.termQuery("description", "逃課"))
                );
        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(constantScoreQueryBuilder).build();

        SearchHits<Student> searchResult = restTemplate.search(searchQuery, Student.class);

        Assert.assertTrue(searchResult.getTotalHits() == 2L);
        searchResult.getSearchHits().forEach(System.out::println);
    }

三種寫法結果都命中兩條

SearchHit{id='1', score=1.0, sortValues=[], content=Student(id=1, name=張三, description=我是一個三好學生), highlightFields={}}
SearchHit{id='2', score=1.0, sortValues=[], content=Student(id=2, name=李四, description=我是一個愛逃課的學生), highlightFields={}}

【5】通過多條件查詢

條件: id必須為1、name可以為張三、description不能包含睡覺

   @Test
    public void searchByMultiConditionTest() {

        ConstantScoreQueryBuilder constantScoreQueryBuilder = QueryBuilders.
                constantScoreQuery(QueryBuilders
                        .boolQuery()
                        .must(QueryBuilders.termQuery("id", 1L))
                        .should(QueryBuilders.termQuery("name", "張三"))
                        .mustNot(QueryBuilders.matchQuery("description", "睡覺"))
                );
        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(constantScoreQueryBuilder).build();

        SearchHits<Student> searchResult = restTemplate.search(searchQuery, Student.class);

        Assert.assertTrue(searchResult.getTotalHits() == 1L);
        searchResult.getSearchHits().forEach(System.out::println);
    }

命中一條

SearchHit{id='1', score=1.0, sortValues=[], content=Student(id=1, name=張三, description=我是一個三好學生), highlightFields={}}

3.更新資料

例:通過id更新其他欄位的資料

@Test
    public void updateDataTest() {

        ImmutableMap<String, Object> paramMap = ImmutableMap.of(
                "name", "張三03",
                "description", "我是一個優秀學生"
        );

        UpdateQuery build = UpdateQuery
                .builder("1")
                .withDocument(Document.from(paramMap))
                .build();

        UpdateResponse response = restTemplate.update(build, IndexCoordinates.of("student"));
        Assert.assertEquals(response.getResult(),UpdateResponse.Result.UPDATED);

    }

3.刪除資料

通過id刪除資料

 @Test
    public void deleteByIdTest() {

        String id = restTemplate.delete("2", Student.class);
        Assert.assertEquals(id, "2");
    }

通過Query刪除資料

 @Test
    public void deleteDataByQueryTest() {

        ConstantScoreQueryBuilder constantScoreQueryBuilder = QueryBuilders.
                constantScoreQuery(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("description", "學生")));
        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(constantScoreQueryBuilder).build();
        
        restTemplate.delete(searchQuery, Student.class);
    }

刪除索引

@Test
    public void deleteIndexTest() {

        restTemplate.indexOps(Student.class).delete();
    }

總結

本文主要介紹了在springboot通過ElasticsearchRestTemplate操作ElasticSearch的一些示例。

相關文章