SpringBoot支持SpringData es

ElasticSearch CRUD

1.springboot springData es

 spring data

         spring对数据访问抽象.这些数据可以放入db,index,nosql等包含以下:

          spring data jpa spring对关系型数据库访问支持

          spring data ES  spring对es数据访问支持

spring data redis等 spring对redis数据访问支持

spring data .....

springboot springdata xxxx

     spring data es

        spring对Es数据访问.和原来spring data jpa对db访问.

     springboot spring data es

         spring data es简化了配置.

2.入门

启动你的elasticsearch

2.1 依赖

注意:我这里使用了lombok

<!--springboot版本仲裁中心-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!--springboot 对spring data es支持-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.8</version>
        <scope>provided</scope>
    </dependency>

</dependencies>

1.1 配置application.yml

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch #指定elasticsearch集群名称
      cluster-nodes: localhost:9300 #9200是图形化界面端 9300是代码端

2.3 入口

@SpringBootApplication
public class EsApplication {
    public static void main(String[] args) {
        SpringApplication.run(EsApplication.class, args);
    }
}

2.4 创建索引文件

注意:索引库名字只能全部是小写

package cn.dyier.doc;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * person索引库
 * 现在ES Doc @Document(index,type) @Id @Feild 建立的是对象与文档直接映射
 * 操作的时wwjEsTest索引库下的person文档
 * @author Lenovo
 */
@Document(indexName = "wwjestest", type="person")
@NoArgsConstructor
@Getter
@Setter
@ToString(exclude = {"all"})
public class PersonDoc {
    /**
     * 文档的id就是对象的id
     */
    @Id
    private Long id;

    /**
     * 没有特殊要求不用@Field
     */
    private Integer age;

    /**
     * keyword不分词
     */
    @Field(type = FieldType.Keyword)
    private String name;

    /**
     * 指定分词类型,分词器,搜索器
     */
    @Field(type = FieldType.Text,
            analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String intro;

    /**
     * 关键字搜索,指定作用于intro 和 name字段
     * 虚拟字段all(所有需要做关键字搜索的值,中间通过空格分隔) zs +" "+ zs is .相当于一个字段代替了很多字段
     */
    @Field(type = FieldType.Text,
            analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String all;

    /**
     * 进行拼接
     * @return 返回拼接后的结果
     */
    public String getAll() {
        return this.name + " " + this.intro;
    }

    public PersonDoc(Long id, Integer age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }
}
PersonDoc

2.5 repository配置

public interface PersonDocRepository extends
        ElasticsearchRepository<PersonDoc, Long> {
}
PersonDocRepository

2.6 创建索引库,添加类型映射,crud,高级查询,排序,分页

package cn.dyier;

import cn.dyier.doc.PersonDoc;
import cn.dyier.repository.PersonDocRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsApplication.class)
public class EsTest {
    //所有的操作都是通过ElasticsearchTemplate
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private PersonDocRepository personDocRepository;

    /**
     * 创建索引库,类型映射 curd(Repository)
     * @throws Exception
     */
    @Test
    public void init() throws Exception {
        System.out.println(elasticsearchTemplate);
        //创建索引库
        elasticsearchTemplate.createIndex(PersonDoc.class);
        //类型映射
        elasticsearchTemplate.putMapping(PersonDoc.class);
    }

    /**
     * 添加或者修改 save
     * id在索引库中存在就是修改
     * @throws Exception
     */
    @Test
    public void testAddOrUpdate() throws Exception {
        PersonDoc personDoc = new PersonDoc(1L, 17, "wwj_test01");
        personDoc.setIntro("这是测试的第一个");
        personDocRepository.save(personDoc);
    }

    /**
     * 批量添加 saveAll
     * @throws Exception
     */
    @Test
    public void testAddAll() throws Exception {
        ArrayList<PersonDoc> personDocs = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            PersonDoc personDoc = new PersonDoc(2L + i, 19 + i, "wwj_" + i);
            personDoc.setIntro("wwj_intro_" + i);
            personDocs.add(personDoc);
        }
        personDocRepository.saveAll(personDocs);
    }

    /**
     * 根据id删除一个 deleteById()
     * @throws Exception
     */
    @Test
    public void testDeleteById() throws Exception {
        personDocRepository.deleteById(14L);
    }

    /**
     * 根据id获取 一个
     * @throws Exception
     */
    @Test
    public void testFindOne() throws Exception {
        System.out.println(personDocRepository.findById(1L));
    }

    /**
     * 查询所有
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {
        personDocRepository.findAll().forEach(System.out::println);
    }

    /**
     * dsl分页+高级查询+排序
     * @throws Exception
     */
    @Test
    public void testDsl() throws Exception {
        //1.创建一个构造器 NativeSearchQueryBuilder
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //2.设置条件 QueryBuilders.boolQuery()
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //2.1 must 必须 all字段包含wwj
        boolQueryBuilder.must(QueryBuilders.matchQuery("all", "wwj"));
        //2.2 filter 过滤 gte大于等于 lte小于等于
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").gte(20).lte(50));
        builder.withQuery(boolQueryBuilder);
        //3.排序 根据id排序
        builder.withSort(SortBuilders.fieldSort("id"));
        //4.分页 页数从0开始
        builder.withPageable(PageRequest.of(0, 10));
        //5.截取字段
        builder.withSourceFilter(new FetchSourceFilter(
                new String[]{"id", "name", "age"}, null));
        //6.查询并封装结果
        NativeSearchQuery build = builder.build();
        //当前页数据
        Page<PersonDoc> page = personDocRepository.search(build);
        //总数
        System.out.println(page.getTotalElements());
        //当前页数据
        System.out.println(page.getContent());
    }
}
精髓..

猜你喜欢

转载自www.cnblogs.com/dyier/p/12339760.html