ElasticSearch查询排序

场景

使用elasticsearch进行查询时,需要在查询时进行排序,而不是查询后进行排序。原本项目中采用的查询方式不能满足,因此对代码进行了优化,原先方式为使用elasticsearch继承的实现,

public interface SensorHistoryDocumentDao extends
		ElasticsearchRepository {
	@Query("{\"bool\" : {\"must\" : {\"field\" : {\"sensor_code\" : \"?0\"}}}}")
    Page findBySensorcode(String sensor_code,Pageable pageable);
}

查询调用sensorHistoryDocumentDao即可:

Iterable searchResult = sensorHistoryDocumentDao.search(queryBuilder);

方案

使用了客户端连接的方式
pom.xml依赖

	
		org.elasticsearch.client
		transport
		5.6.3
	

客户端连接,需要先配置参数elasticsearchIp,elasticsearchPort

	Client client = TransportClient
				.builder()
				.build()
				.addTransportAddress(
						new InetSocketTransportAddress(InetAddress.getByName(elasticsearchIp), elasticsearchPort));

获取构造器

	BoolQueryBuilder queryBuilder = QueryBuilders
		.boolQuery()
		.must(QueryBuilders.matchQuery("sensor_code", sensorHistoryDto.getSensor_code()))
		.must(QueryBuilders.rangeQuery("createtime")
		.gt(stratTime).lt(endTime)
		.includeLower(true).includeUpper(true));// 时间为long类型

执行查询

		SearchResponse response = client.prepareSearch().setSize(100).setQuery(queryBuilder)
				.addSort(SortBuilders.fieldSort("createtime").order(SortOrder.DESC)).execute().actionGet();

你可能感兴趣的:(java)