使用go-mysql-elasticsearch
风中勁草 2019-10-08 JAVAElasticSearch
由于项目需要进行查找所以需要使用elasticsearch但是需要将mysql里的内容同步至elasticsearch所以使用go-mysql-elasticsearch进行同步,go-mysql-elasticsearch 从mysql实时同步数据到elasticsearch 简单使用方法介绍
# pom.xml配置
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--引入全局搜索Elasticsearch-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
# 创建接口继承ES接口
public interface ArticleRepository extends ElasticsearchRepository<Article,Integer> {
}
1
2
3
2
3
# 注入
@Autowired
ArticleRepository articleRepository;
# 实现方法
QueryBuilder queryBuilder;
Pageable pageable = PageRequest.of(页码,显示条数);
if(key.equals("")){
queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("参数").gt(0));
}else {
queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery(索引,关键词)).must(QueryBuilders.rangeQuery("参数").gt(0));
}
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(queryBuilder);
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(排序索引).order(SortOrder.DESC));
nativeSearchQueryBuilder.withPageable(pageable);
Page<Article> results = articleRepository.search(nativeSearchQueryBuilder.build());
count = results.getTotalPages();
List<Article> list = new ArrayList<Article>();
for(Article article:results.getContent()){
list.add(article);
}
return list;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19