版本对应
本次整合的elasticsearch版本为7.6.2,对应springboot版本号为2.3.3
pom文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sunyuqi</groupId>
<artifactId>springboot-elasticsearch</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-elasticsearch</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>9</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
elasticsearch:
rest.uris: http://127.0.0.1:9200
实体类
package com.sunyuqi.es.entity;
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;
//索引库名为index_name,类型为article,分片为5,每片备份1片
@Document(indexName = "index_name", type = "article",shards = 5,replicas = 1)
public class Article {
@Id
@Field(type = FieldType.Long, store = true)
private long id;
@Field(type = FieldType.Text, store = true, analyzer = "ik_smart")
private String title;
@Field(type = FieldType.Text, store = true, analyzer = "ik_smart")
private String content;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
ElasticsearchRepository接口
自定义接口需要继承ElasticsearchRepository接口,接口方法命名规则类似spring data jpa,无需实现具体接口方法
package com.sunyuqi.es.repositories;
import com.sunyuqi.es.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
List<Article> findByTitle(String title);
List<Article> findByContent(String content);
List<Article> findByTitleOrContent(String title, String content);
List<Article> findByTitleOrContent(String title, String content, Pageable pageable);
}
springboot引导类
package com.sunyuqi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootElasticsearchApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootElasticsearchApplication.class, args);
}
}
测试类
package com.sunyuqi;
import com.sunyuqi.es.entity.Article;
import com.sunyuqi.es.repositories.ArticleRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.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.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.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootElasticsearchApplication.class)
class SpringbootElasticsearchApplicationTests {
@Autowired
private ArticleRepository articleRepository;
@Autowired
private ElasticsearchRestTemplate template;
//添加文档
@Test
public void addDocument() throws Exception {
for (int i = 0; i <= 20; i++) {
//创建一个Article对象
Article article = new Article();
article.setId(i);
article.setTitle("测试的标题" + i);
article.setContent("测试的内容"+i);
//把文档写入索引库
articleRepository.save(article);
}
}
@Test
public void deleteDocumentById() throws Exception {
articleRepository.deleteById(1l);
//全部删除
// articleRepository.deleteAll();
}
//查询所有文档
@Test
public void findAll() throws Exception {
Iterable<Article> articles = articleRepository.findAll();
for (Article article : articles) {
System.out.println(article);
}
}
//根据ID查询
@Test
public void testFindById() throws Exception {
Article article = template.get("14", Article.class);
System.out.println(article);
}
//匹配标题,精准匹配
@Test
public void testFindByTitle() throws Exception {
List<Article> list = articleRepository.findByTitle("标题");
for (Article article : list) {
System.out.println(article);
}
}
//匹配标题或者内容
@Test
public void testFindByTitleOrContent() throws Exception {
Pageable pageable = PageRequest.of(1, 5);
List<Article> articles = articleRepository.findByTitleOrContent("maven", "内容", pageable);
for (Article article : articles) {
System.out.println(article);
}
}
//分词查询
@Test
public void testNativeSearchQuery() throws Exception {
//创建一个查询对象
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.queryStringQuery("内容包含").defaultField("content"))
.withPageable(PageRequest.of(0, 15))
.build();
//执行查询
SearchHits<Article> search = template.search(query, Article.class);
List<SearchHit<Article>> searchHits = search.getSearchHits();
for (SearchHit<Article> searchHit : searchHits) {
System.out.println(searchHit.getContent());
}
//获取聚合结果
if (search.hasAggregations()) {
ParsedAvg parsedAvg = search.getAggregations().get("avg_price");
Assertions.assertNotNull(parsedAvg, "无聚合结果");
System.out.println(parsedAvg.getValue());
}
}
}
添加文档时如果索引库不存在则会自动创建