Elasticsearch学习(三)springboot整合ElasticSearch

文章目录

  • 前言
  • 一、整合步骤
    • 1、引入ElasticSearch依赖
    • 2、添加配置文件
    • 3、创建实体类
    • 4、创建测试类
  • 三、测试
    • 1.创建索引
    • 2.添加数据
    • 3.检索数据
      • 【1】通过id查询
      • 【2】通过keyword查询
      • 【3】通过text查询
      • 【4】通过text多值查询
      • 【5】通过多条件查询
    • 3.更新数据
    • 3.删除数据
  • 总结


前言

本篇主要对介绍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的一些示例。

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