赞
踩
Spring Boot与Elasticsearch整合的官方文档:Spring Data Elasticsearch
Spring Boot与Elasticsearch的版本要匹配对应,否则后面会出问题。
下表显示了 Spring Data release trains 的 Elasticsearch 版本和其中包含的 Spring Data Elasticsearch 版本,以及引用该特定 Spring Data release trains 的 Spring Boot 版本:
这里使用的是 SpringBoot-2.3.4.RELEASE 和 ElasticSearch-7.6.2
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- server:
- port: 8033
- spring:
- elasticsearch:
- rest:
- uris: 192.168.1.179:9200
- @Document(indexName = "stu", shards = 3, replicas = 0)
- public class Stu {
-
- @Id
- private Long stuId;
-
- @Field(store = true, analyzer = "ik_max_word", type = FieldType.Text)
- private String name;
-
- @Field(store = true, type = FieldType.Integer)
- private Integer age;
-
- @Field
- private Float money;
-
- @Field
- private boolean isMarried;
-
-
- // getter、setter、toString() 省略
- }
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = Application.class)
- public class ESTest {
-
- @Autowired
- private ElasticsearchRestTemplate esTemplate;
-
- ......
- }
这里使用 ElasticsearchRestTemplate 方式执行增删改查
- @Test
- public void createIndex(){
- esTemplate.indexOps(Stu.class).create();
- }
- @Test
- public void deleteIndex() {
- esTemplate.indexOps(Stu.class).delete();
- }
- @Test
- public void existIndex() {
- boolean isExist = esTemplate.indexOps(Stu.class).exists();
- System.out.println(isExist);
- }
- @Test
- public void addDoc() {
-
- Stu stu0 = new Stu(10010L, "didiok", 18, 100.5f, true);
- esTemplate.save(stu0);
-
- Stu stu1 = new Stu(10011L, "Rede", 20, 88.5f, true);
- Stu stu2 = new Stu(10012L, "放下", 22, 108.5f, false);
-
- List<Stu> stuList = new ArrayList<>();
- stuList.add(stu1);
- stuList.add(stu2);
- esTemplate.save(stuList);
- }
- @Test
- public void deleteDoc(){
- esTemplate.delete("10010", Stu.class);
- }
- @Test
- public void getDoc(){
- System.out.println(esTemplate.get("10011", Stu.class));
- }
- @Test
- public void updateDoc(){
- Map<String, Object> stuMap = new HashMap<>();
- stuMap.put("name", "秦王嬴政");
- stuMap.put("age", 2000);
-
- Document doc = Document.from(stuMap);
-
- UpdateQuery updateQuery = UpdateQuery.builder("10011")
- .withDocument(doc)
- .build();
- IndexCoordinates indexCoordinate = IndexCoordinates.of("stu");
-
- esTemplate.update(updateQuery, indexCoordinate);
- }
- /**
- * 搜索数据
- */
- @Test
- public void searchStu(){
- Pageable pageable = PageRequest.of(0, 10);
-
- SortBuilder sortBuilder = new FieldSortBuilder("money")
- .order(SortOrder.ASC);
- SortBuilder sortBuilderName = new FieldSortBuilder("name.keyword") # name 有两种类型:text和keyword,其中name.keyword是指其为keyword类型的字段
- .order(SortOrder.DESC);
- NativeSearchQuery query =new NativeSearchQueryBuilder()
- .withQuery(QueryBuilders.matchQuery("name", "美丽 漂亮"))
- .withPageable(pageable)
- .withSort(sortBuilder)
- .withSort(sortBuilderName)
- .build();
- SearchHits<Stu> hits = esTemplate.search(query, Stu.class);
- System.out.println(hits.getSearchHits());
- }
- @Test
- public void highlight(){
-
- String preTag = "<font color='red'>";
- String postTag = "</font>";
- NativeSearchQuery query = new NativeSearchQueryBuilder()
- .withQuery(QueryBuilders.matchQuery("name", "美丽可爱"))
- .withHighlightFields(new HighlightBuilder.Field("name")
- .preTags(preTag)
- .postTags(postTag))
- .build();
-
- SearchHits<Stu> hits = esTemplate.search(query, Stu.class);
- List<SearchHit<Stu>> stuHits = hits.getSearchHits();
-
- List<Stu> hlList = new ArrayList<>();
- for(SearchHit<Stu> h : stuHits){
- List<String> hlField = h.getHighlightField("name");
- String hlValue = hlField.get(0);
-
- Stu content = h.getContent();
- content.setName(hlValue);
- hlList.add(content);
- }
- System.out.println(hlList);
- }
- @Document(indexName = "stu", shards = 3, replicas = 0)
- public class Stu {
-
- @Id
- private Long stuId;
-
- @Field(store = true, analyzer = "ik_max_word", type = FieldType.Text)
- private String name;
-
- @Field(store = true, type = FieldType.Integer)
- private Integer age;
-
- @Field
- private Float money;
-
- @Field
- private boolean isMarried;
-
-
- // getter、setter、toString() 省略
- }
- /**
- * @Author: liuss
- * @DateTime: 2023-04-22 13:34
- * @Description:
- * ElasticsearchRepository<T, ID> T:实体类泛型,ID:ES库中索引的主键类型
- */
- public interface StuMapper extends ElasticsearchRepository<Stu, String> {
-
- }
3.1 ElasticsearchRepository本身自带了一些简单curd方法,如下图
使用es自带的方法:
- @Test
- public void searchStu2(){
- Optional<Stu> stu = stuMapper.findById("10021");
- Iterable<Stu> stu2 = stuMapper.findAll();
- System.out.println(stu);
- System.out.println(stu2);
- }
3.2 使用自定义的方法
Keyword | Sample | Elasticsearch Query String |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
可以自定义方法如下:
- public interface StuMapper extends ElasticsearchRepository<Stu, String> {
-
- List<Stu> findStusByName(String name);
- }
使用自定义方法查询:
- @Test
- public void searchStu3(){
- List<Stu> stus = stuMapper.findStusByName("didiok");
- System.out.println(stus);
- }
这只是其中一部分,更多内容可以参照官方文档:Spring Data Elasticsearch
- package com.test;
-
- import java.util.*;
-
- import org.elasticsearch.index.query.QueryBuilders;
- import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
- import org.elasticsearch.search.sort.FieldSortBuilder;
- import org.elasticsearch.search.sort.SortBuilder;
- import org.elasticsearch.search.sort.SortOrder;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.json.GsonJsonParser;
- import org.springframework.boot.json.JsonParser;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.data.domain.PageRequest;
- import org.springframework.data.domain.Pageable;
- import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
- import org.springframework.data.elasticsearch.core.SearchHit;
- import org.springframework.data.elasticsearch.core.SearchHits;
- import org.springframework.data.elasticsearch.core.document.Document;
- import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
- import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
- import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
- import org.springframework.data.elasticsearch.core.query.UpdateQuery;
- import org.springframework.test.context.junit4.SpringRunner;
-
- import com.didiok.Application;
- import com.didiok.es.mapper.StuMapper;
- import com.didiok.es.pojo.Stu;
- import com.didiok.utils.JsonUtils;
-
- /**
- * @Author: liuss
- * @DateTime: 2023-04-21 16:47
- * @Description:
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = Application.class)
- public class ESTest {
-
- @Autowired
- private ElasticsearchRestTemplate esTemplate;
-
- /**
- * 创建索引
- */
- @Test
- public void createIndex(){
- esTemplate.indexOps(Stu.class).create();
- }
-
- /**
- * 删除索引
- */
- @Test
- public void deleteIndex() {
- esTemplate.indexOps(Stu.class).delete();
- }
-
- /**
- * 判断索引是否存在
- */
- @Test
- public void existIndex() {
- boolean isExist = esTemplate.indexOps(Stu.class).exists();
- System.out.println(isExist);
- }
-
- /**
- * 新增文档数据
- */
- @Test
- public void addDoc() {
-
- Stu stu0 = new Stu(10010L, "didiok", 18, 100.5f, true);
- esTemplate.save(stu0);
-
- Stu stu1 = new Stu(10011L, "Rede", 20, 88.5f, true);
- Stu stu2 = new Stu(10012L, "放下", 22, 108.5f, false);
-
- List<Stu> stuList = new ArrayList<>();
- stuList.add(stu1);
- stuList.add(stu2);
- esTemplate.save(stuList);
- }
-
- /**
- * 根据文档id删除数据
- */
- @Test
- public void deleteDoc(){
- esTemplate.delete("10010", Stu.class);
- }
-
- /**
- * 查询文档数据
- */
- @Test
- public void getDoc(){
- System.out.println(esTemplate.get("10011", Stu.class));
- }
-
- /**
- * 修改文档数据
- */
- @Test
- public void updateDoc(){
- Map<String, Object> stuMap = new HashMap<>();
- stuMap.put("name", "秦王嬴政");
- stuMap.put("age", 2000);
-
- Document doc = Document.from(stuMap);
-
- UpdateQuery updateQuery = UpdateQuery.builder("10011")
- .withDocument(doc)
- .build();
- IndexCoordinates indexCoordinate = IndexCoordinates.of("stu");
-
- esTemplate.update(updateQuery, indexCoordinate);
- }
-
- /******************** 分词搜索 ********************/
-
- /**
- * 初始化数据
- */
- @Test
- public void init() {
-
- esTemplate.indexOps(Stu.class).delete();
- esTemplate.indexOps(Stu.class).create();
-
- Stu stu0 = new Stu(10020L, "didiok", 18, 100.5f, true);
- Stu stu1 = new Stu(10021L, "放下", 20, 88.5f, true);
- Stu stu2 = new Stu(10022L, "里德先生", 22, 96.5f, false);
- Stu stu3 = new Stu(10023L, "可爱的漂亮的小哥哥", 26, 108.5f, false);
- Stu stu4 = new Stu(10024L, "美丽的祖国", 28, 108.6f, true);
- Stu stu5 = new Stu(10025L, "美丽的漂亮的小姐姐", 16, 18.5f, false);
- Stu stu6 = new Stu(10026L, "超级赛亚人", 29, 100.5f, true);
-
- List<Stu> stuList = new ArrayList<>();
- stuList.add(stu0);
- stuList.add(stu1);
- stuList.add(stu2);
- stuList.add(stu3);
- stuList.add(stu4);
- stuList.add(stu5);
- stuList.add(stu6);
- esTemplate.save(stuList);
-
- }
-
- /**
- * 搜索数据
- */
- @Test
- public void searchStu(){
- Pageable pageable = PageRequest.of(0, 10);
-
- SortBuilder sortBuilder = new FieldSortBuilder("money")
- .order(SortOrder.DESC);
- SortBuilder sortBuilderName = new FieldSortBuilder("name.keyword")
- .order(SortOrder.ASC);
- NativeSearchQuery query =new NativeSearchQueryBuilder()
- .withQuery(QueryBuilders.matchQuery("name", "美丽 漂亮"))
- .withPageable(pageable)
- .withSort(sortBuilder)
- .withSort(sortBuilderName)
- .build();
- SearchHits<Stu> hits = esTemplate.search(query, Stu.class);
- System.out.println(hits.getSearchHits());
- }
-
- /**
- * 高亮搜索
- */
- @Test
- public void highlight(){
-
- String preTag = "<font color='red'>";
- String postTag = "</font>";
- NativeSearchQuery query = new NativeSearchQueryBuilder()
- .withQuery(QueryBuilders.matchQuery("name", "美丽可爱"))
- .withHighlightFields(new HighlightBuilder.Field("name")
- .preTags(preTag)
- .postTags(postTag))
- .build();
-
- SearchHits<Stu> hits = esTemplate.search(query, Stu.class);
- List<SearchHit<Stu>> stuHits = hits.getSearchHits();
-
- List<Stu> hlList = new ArrayList<>();
- for(SearchHit<Stu> h : stuHits){
- List<String> hlField = h.getHighlightField("name");
- String hlValue = hlField.get(0);
-
- Stu content = h.getContent();
- content.setName(hlValue);
- // String contentJson = JsonUtils.objectToJson(h.getContent());
- // JsonParser jj = new GsonJsonParser();
- // Map<String, Object> hlMap = jj.parseMap(contentJson);
- // hlMap.put("name", hlValue);
- hlList.add(content);
- }
- System.out.println(hlList);
- }
-
- @Autowired
- private StuMapper stuMapper;
-
- /**
- * 使用ElasticsearchRepository自带的方法查询
- */
- @Test
- public void searchStu2(){
- Optional<Stu> stu = stuMapper.findById("10021");
- Iterable<Stu> stu2 = stuMapper.findAll();
- System.out.println(stu);
- System.out.println(stu2);
- }
-
- /**
- * 使用自定义方法查询
- */
- @Test
- public void searchStu3(){
- List<Stu> stus = stuMapper.findStusByName("didiok");
- System.out.println(stus);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。