Spring-Boot-Search

Spring Boot 与检索


在Docker中安装

同样的先下载镜像

1
docker pull elasticsearch

如果觉得下载的慢的可以换中国源:

1
docker pull registry.docker-cn.com/library/elasticsearch

因为Elasticsearch是使用Java写的,默认会使用2G内存空间,如果空间不足,可以在启动时限制内存空间

1
docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p9300:9300 --name yourname elasticsearch
  • Web通信: 9200
  • 节点之间的通信(分布式情形下): 9300
  • 初始占用内存: -Xms
  • 最大占用内存: -Xmx

在Spring Boot中使用

application.propertiesapplication.yml中指定Elasticsearch的位置

1
spring.elasticsearch.jest.uris=http://localhost:9200

使用Jest操作Elasticsearch

引入依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>6.3.1</version>
</dependency>

自动注入

1
2
@Autowired
JestClient jestClient

新建索引

1
2
3
4
5
6
7
Index index = new Index.Builder(object).index("demo").type("news").build();

try{
jestClient.execute(index);
} catch (IOException e){
e.printStackTrace();
}

搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//查询表达式
String json = "{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"last_name\" : \"Smith\"\n" +
" }\n" +
" }\n" +
"}";

Search search = new Search.Builder(json).addIndex("demo").addType("news").build();

try{
jestClient.execute(search);
} catch (IOException e){
e.printStackTrace();
}

具体到Elasticsearch: 权威指南查看,但由于中文版指南最后一次更新是2016年,可能过时了

使用Spring Data Elasticsearch

使用Spring Data Elasticsearch要注意版本问题,下面是版本号的对应情况

spring data elasticsearch elasticsearch
3.2.x 6.5.0
3.1.x 6.2.2
3.0.x 5.5.0
2.1.x 2.4.0
2.0.x 2.2.0
1.3.x 1.5.2

ElasticsearchRepository

创建一个用于保存的实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Document(indexName = "demoIndex", type = "demoType")
public class Demo {
private Integer id;
private String name;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String toString(){
return "Demo{" +
"id=" + id +
"name'" + name + '\'' +
'}';
}
}

创建一个ElasticsearchRepository的子接口,ElasticsearchRepository<T, ID extends Serializable>需要接收两个类型,一是要保存的对象,而是对象的主键(要可序列化的)

1
2
3
4
5
6
@Component
public interface DemoRepository extends ElasticsearchRepository<Object, Object>{

//模糊搜索,不用自己去实现
public List<Demo> findByNameLike(String name);
}

自动注入

1
2
3
4
5
6
7
8
@Autowired
DemoRepository demoRepository

public void demo(){
Object object = new Object();
demoRepository.index(object);
demoRepository.findByNameLike("demo");
}

ElasticsearchTemplate

1
2
3
4
5
6
7
8
9
10
@Autowired
ElasticsearchTemplate elasticsearchTemplate;

SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withFilter(boolFilter().must(termFilter("id", documentId)))
.build();

Page<SampleEntity> sampleEntities =
elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class);