一次查询多个字段,每个字段对应一个值。如查询条件属性plan_id、sku_id,值分别为:11、12
1、json请求格式如下
{
"from": 1,
"size": 20,
"query": {
"bool": {
"filter": [{
"term": {
"plan_id": {
"value": 11,
"boost": 1
}
}
}, {
"term": {
"sku_id": {
"value": 12,
"boost": 1
}
}
}],
"adjust_pure_negative": true,
"boost": 1
}
},
"sort": [{
"create_time": {
"order": "desc"
}
}]
}
2、Java客户端代码如下:
import java.util.Iterator;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestClient {
private static final Logger logger = LoggerFactory.getLogger(QueryUtils.class);
public static void main(String[] args) {
QueryUtils esQuery = new QueryUtils();
Long planId = 11L;
Long skuId = 12L;
int from = 1;
int size = 20;
String sortName = "create_time";
BoolQueryBuilder builder = QueryBuilders.boolQuery();
builder.filter(QueryBuilders.termQuery("plan_id", planId));
builder.filter(QueryBuilders.termQuery("sku_id", skuId));
SearchResponse searchResponse = esQuery.queryByPage(builder, from, size, sortName, SortOrder.DESC);
if(searchResponse != null) {
logger.info("totalHits:{}",searchResponse.getHits().getTotalHits());
Iterator iterator = searchResponse.getHits().iterator();
while (iterator.hasNext()){
SearchHit hit = iterator.next();
logger.info("sourceAsString:{}",hit.getSourceAsString());
}
esQuery.close();
}
}
}
一次查询单个字段,多个值。如查询条件属性skuId,值:12、13
1、json格式如下:
{
"from": 1,
"size": 20,
"query": {
"terms": {
"skuId": [12, 13],
"boost": 1.0
}
},
"sort": [{
"create_time": {
"order": "desc"
}
}]
}
2、java客户端代码如下:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestClient {
private static final Logger logger = LoggerFactory.getLogger(QueryUtils.class);
public static void main(String[] args) {
QueryUtils esQuery = new QueryUtils();
int from = 1;
int size = 20;
String sortName = "create_time";
List skuIds = new ArrayList();
skuIds.add(12L);
skuIds.add(3L);
QueryBuilder builder = QueryBuilders.termsQuery("skuId", skuIds);
SearchResponse searchResponse = esQuery.queryByPage(builder, from, size, sortName, SortOrder.DESC);
if(searchResponse != null) {
logger.info("totalHits:{}",searchResponse.getHits().getTotalHits());
Iterator iterator = searchResponse.getHits().iterator();
while (iterator.hasNext()){
SearchHit hit = iterator.next();
logger.info("sourceAsString:{}",hit.getSourceAsString());
}
esQuery.close();
}
}
}
查询工具类如下:
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class QueryUtils {
private final Logger logger = LoggerFactory.getLogger(QueryUtils.class);
private static RestHighLevelClient restHighLevelClient;
private static final String HOST = "xxxx";
private static final String USERNAME = "xxx";
private static final String PASSWORD = "xxx";
public QueryUtils() {
restHighLevelClient = buildClient();
}
/**
* 初始化客户端
* @return
*/
protected RestHighLevelClient buildClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(HOST))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
Header[] defaultHeaders = new Header[]{new BasicHeader("Host", HOST)};
restClientBuilder.setDefaultHeaders(defaultHeaders);
return new RestHighLevelClient(restClientBuilder);
}
/**
* 释放连接
*/
public void close() {
try {
if (restHighLevelClient != null) {
restHighLevelClient.close();
}
} catch (Exception e) {
logger.error("Error closing ElasticSearch client: ", e);
}
}
/**
* 分页条件查询
* @param builders
* @param from
* @param size
* @param sortName
* @param order
* @return
*/
public SearchResponse queryByPage(QueryBuilder builders, int from, int size,String sortName, SortOrder order) {
SearchRequest searchRequest = new SearchRequest("xxx");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(builders);
if (from > 0) {
searchSourceBuilder.from(from);
}
searchSourceBuilder.sort(sortName, order);
if (size > 0) {
searchSourceBuilder.size(size);
}
searchRequest.source(searchSourceBuilder);
logger.info("searchRequest==>> {}", searchRequest.toString());
SearchResponse response = null;
try {
response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
logger.error("occur an exception:{}",e.getMessage(),e);
}
return response;
}
}