SpringBoot集成ElasticSearch并操作Es
pom
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.penny</groupId>
<artifactId>springbootdataes</artifactId>
<version>1.0-SNAPSHOT</version>
<!--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>
</dependencies>
</project>
主要引入它
<!--springboot 对spring data es支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
通过spring data Es简便快捷操作Es
创建application.yml
application.yml
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300 #9200是图形界面端,9300代码端
开启es服务
开启Kibana server
然后创建一个测试doc
package com.penny.doc;
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;
//操作的是test索引库下面的person类型的文档
@Document(indexName = "test",type = "person")
public class PersonDoc {
@Id
private Long id;
private Integer age;
//有特殊要求才用@Field
//KeyWord不分词,Text要分词
@Field(type = FieldType.Keyword)
private String name;
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String intro;
//虚拟字段all,用来进行关键词搜索,中间用空格分隔
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String all;
//此处进行返回值的拼接,中间空格隔开
public String getAll() {
return this.name+" "+this.intro;
}
public void setAll(String all) {
this.all = all;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public PersonDoc(Long id, Integer age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public PersonDoc() {
}
@Override
public String toString() {
return "PersonDoc{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
", intro='" + intro + '\'' +
", all='" + all + '\'' +
'}';
}
}
创建一个数据访问接口repository
repository
package com.penny.repository;
import com.penny.doc.PersonDoc;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface PersonDocRepository extends ElasticsearchRepository<PersonDoc,Long> {
}
创建一个服务启动入口
EsApp
package com.penny;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EsApp {
public static void main(String[] args) {
SpringApplication.run(EsApp.class, args);
}
}
再创建一个测试类
EsTest
package com.penny;
import com.penny.doc.PersonDoc;
import com.penny.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;
import java.util.List;
import java.util.Optional;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsApp.class)
public class EsTest {
@Autowired
private ElasticsearchTemplate template;
@Autowired
private PersonDocRepository repository;
@Test
public void test(){
System.out.println(template);
//创建索引
template.createIndex(PersonDoc.class);
//类型映射
template.putMapping(PersonDoc.class);
}
//增加或删除
@Test
public void testAddOrEdit(){
PersonDoc doc = new PersonDoc(1L,20,"zc");
doc.setIntro("i'm a person");
repository.save(doc);
}
//批量添加
@Test
public void testAddBatch(){
List<PersonDoc> docs = new ArrayList<>();
for (int i = 0; i <40 ; i++) {
PersonDoc doc = new PersonDoc();
doc.setIntro("test"+i);
docs.add(doc);
}
repository.saveAll(docs);
for (PersonDoc doc : docs) {
System.out.println(doc);
}
}
//删除
@Test
public void testDel(){
repository.deleteById(1L);
}
//获取一个
@Test
public void testGetOne(){
Optional<PersonDoc> one = repository.findById(2L);
System.out.println(one);
}
//获取所有
@Test
public void testGetAll(){
Class<? extends Iterable> all = repository.findAll().getClass();
System.out.println(all);
}
//dsl分页+高级查询+排序
@Test
public void testDsl(){
//创建一个构建器 NativeSearchQueryBuilder
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//设置条件 BoolQuery query bool
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//must指定条件
boolQuery.must(QueryBuilders.matchQuery("all","zc"));
//fiter过滤条件
boolQuery.filter(QueryBuilders.rangeQuery("age").gte(18).lte(50));
builder.withQuery(boolQuery);
//排序
builder.withSort(SortBuilders.fieldSort("id"));
//分页
builder.withPageable(PageRequest.of(0, 10));
//截取字段
builder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "name", "age"}, null));
//查询并封装结果
NativeSearchQuery build = builder.build();
Page<PersonDoc> page = repository.search(build);
System.out.println(page.getTotalElements());
System.out.println(page.getContent());
}
}
随后访问http://localhost:5601/,选择Dev Tools
随后输入之前在PersonDoc开头设置的路径条件
.
即可看到结果值
在Dsl中,
1.NativeSearchQueryBuilder用于创建一个构造器
子方法
1.1.withQuery(query)用于做高级查询,条件过滤
1.2.withSort(SortBuilders.fieldSort(“排序字段”))用于排序
1.3.withPageable(PageRequest.of(0, 10))用于分页
1.4.withSourceFilter(new FetchSourceFilter(new String[]{“id”, “name”, “age”}, null))用于截取字段
2.BoolQueryBuilder用于做高级查询,条件过滤
子方法
2.1.must(query)用于指定条件
2.2.filter(query)用于过滤条件