1、配置Elastic Search
# application.yml
spring:
elasticsearch:
rest:
uris: http://localhost:9200 # 设置Elastic Search的连接地址
username: username # 设置Elastic Search的用户名
password: password # 设置Elastic Search的密码
connection-request-timeout: 5000 # 设置连接请求超时时间
socket-timeout: 5000 # 设置Socket超时时间
max-connections: 100 # 设置最大连接数
max-connections-per-route: 10 # 设置每个路由的最大连接数
注释说明:
spring.elasticsearch.rest.uris
:设置Elastic Search的连接地址,这里的示例是本地地址http://localhost:9200
,根据实际情况修改。spring.elasticsearch.username
和spring.elasticsearch.password
:设置Elastic Search的用户名和密码,如果没有设置访问控制,这两项可以省略。spring.elasticsearch.connection-request-timeout
和spring.elasticsearch.socket-timeout
:设置连接请求超时时间和Socket超时时间,单位是毫秒。spring.elasticsearch.max-connections
和spring.elasticsearch.max-connections-per-route
:设置最大连接数和每个路由的最大连接数。
2、使用Elastic Search查询分页
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
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.stereotype.Service;
@Service
public class ElasticsearchService {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public SearchResponse searchWithPagination(int page, int size) {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery()) // 设置查询条件,这里示例为查询所有
.withPageable(PageRequest.of(page, size)) // 设置分页信息
.withSort(SortBuilders.fieldSort("field").order(SortOrder.DESC)) // 设置排序字段和排序方式
.build();
return elasticsearchRestTemplate.query(searchQuery, response -> response);
}
}
注释说明:
ElasticsearchRestTemplate
:使用Spring Data Elasticsearch提供的ElasticsearchRestTemplate来进行Elastic Search的操作。NativeSearchQueryBuilder
:用于构建Elastic Search的查询条件。QueryBuilders.matchAllQuery()
:示例中使用了matchAllQuery()
查询所有数据,根据实际需求修改查询条件。PageRequest.of(page, size)
:设置分页信息,page
表示页码,size
表示每页大小。SortBuilders.fieldSort("field").order(SortOrder.DESC)
:设置排序字段和排序方式,这里示例为按某个字段降序排序,根据实际需求修改排序字段。elasticsearchRestTemplate.query(searchQuery, response -> response)
:执行查询操作,并返回查询结果。