关于Elasticsearch MultiSearch 查询

关于Elasticsearch MultiSearch 查询,一个请求可同时支持多个查询

关于Elasticsearch  MultiSearch 查询,一个请求可同时支持多个查询

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.elasticsearch.action.search.MultiSearchRequestBuilder;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;


import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

/**
* @Author :PENG.ZHANG
* @Description :
* @Date : Create in 15:22 2018/6/4
* Created by Administrator on 2018/6/4.
*/
public class MultiSearch {
private static final Logger logger = LogManager.getLogger(MultiSearch.class);

public static void main(String[] args) {
try {

Settings settings = Settings.settingsBuilder()
.put("cluster.name", "elasticsearch").build();
// 创建客户端
Client client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.81"), 9300));
// 初始化两个查询
SearchRequestBuilder srb1 =client
.prepareSearch().setQuery(QueryBuilders.boolQuery()
.must(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("idNumb","2028"))))
.setExplain(true);

SearchRequestBuilder srb2 = client
.prepareSearch().setQuery(QueryBuilders.boolQuery()
.must(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("idNumb","2035"))))
.setExplain(true);
//将query对象放入集合中模仿传参
List<SearchRequestBuilder> arrList = new ArrayList<>();
arrList.add(srb1);
arrList.add(srb2);
//MultiSearch查询
MultiSearchRequestBuilder sr = null;
for (SearchRequestBuilder ss : arrList){
sr = client.prepareMultiSearch().add(ss);
}
MultiSearchResponse ss = sr.execute().actionGet();
long nbHits = 0;
for (MultiSearchResponse.Item item : ss.getResponses()) {
SearchResponse response = item.getResponse();
nbHits += response.getHits().getTotalHits();
System.out.println("print result :"+nbHits);
}
} catch (Exception e) {
logger.error("exception:", e);
}
}

}
  • 发表于 2018-06-04 16:32
  • 阅读 ( 1877 )
  • 分类:大数据

0 条评论

请先 登录 后评论
不写代码的码农
张鹏

大数据工程师

95 篇文章

作家榜 »

  1. 张鹏 95 文章
  2. 0 文章
  3. 赵科 0 文章
  4. 王孖珺397954227 0 文章