使用Java API搜索多个elasticsearch的索引

时间:2018-06-11 10:06:56

标签: java elasticsearch elastic-stack

能够使用一个索引搜索elasticsearch,但我想搜索多个索引和源。

请找到以下用于搜索一个index和一个source

的代码
private final String INDEX = "my_index";
private final String TYPE = "doc";
private final String SOURCE = "doct_name";

GetRequest getRequest = new GetRequest(INDEX, TYPE, SOURCE);
getRequest.routing(name);

GetResponse getResponse = null;

try {
    getResponse = restHighLevelClient.get(getRequest);
} catch (java.io.IOException e){
    e.getLocalizedMessage();
}
SearchRequest searchRequest = new SearchRequest(INDEX); 
searchRequest.types(TYPE);

String star="*";
String query=star.concat(name).concat("*");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
QueryStringQueryBuilder qsQueryBuilder = new QueryStringQueryBuilder(query); 
qsQueryBuilder.defaultField("*");
searchSourceBuilder.query(qsQueryBuilder); 
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try {
     searchResponse = restHighLevelClient.search(searchRequest);
} catch (IOException e) {
    e.getLocalizedMessage();
}

2 个答案:

答案 0 :(得分:0)

只需使用SearchRequest的varargs构造函数传递多个索引名称。

  

构建针对索引的新搜索请求。没有指数   这里提供的意思是搜索将针对所有索引运行。

SearchRequest searchRequest = new SearchRequest(INDEX, INDEX2)

答案 1 :(得分:0)

你可以使用数组索引Searchrequest构造函数。

String indices[]-{INDEX, INDEX2}

this.searchRequest = new SearchRequest(indices);