我认为下面的代码应该有所帮助。请注意,您可以创建此链接TransportClient client
中提到的实例
为了使用Java API执行搜索,下面的代码应该会有所帮助:
SearchResponse response = client.prepareSearch("index1", "index2")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("type", "tweet")) // Query
.setFrom(0).setSize(60) // Set whatever size you'd want
.get();
以下一些有用的 API 链接:
注意: ES 建议人们迁移到此链接中提到的 Java Rest Client ,本指南应该可以帮助您了解如何从 Java API 迁移到使用 REST Client。
更新答案:
假设我有两个索引
user
username
有值的字段Opster
tweet
data
有值的字段some text
为了简单起见,我将两个字段都设置keyword
为
您正在寻找的内容如下
在 Elasticsearch 的查询 DSL 中:
POST /_search
{
"query": {
"bool": {
"should": [
{
"bool": {
"must": [
{
"term": {
"_index": "user"
}
},
{
"term": {
"username": "Opster"
}
}
]
}
},
{
"bool": {
"must": [
{
"term": {
"_index": "tweet"
}
},
{
"term": {
"data": "some text"
}
}
]
}
}
]
}
}
}
Java API:
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
public class QueryForMultipleIndexes {
public static void main(String[] args) throws UnknownHostException {
// on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
QueryBuilder firstQuery = new BoolQueryBuilder()
.must(QueryBuilders.termQuery("_index", "user"))
.must(QueryBuilders.termQuery("username", "Opster"));
QueryBuilder secondQuery = new BoolQueryBuilder()
.must(QueryBuilders.termQuery("_index", "tweet"))
.must(QueryBuilders.termQuery("data", "some text"));
//This is the should clause which in turn contains two must clause
QueryBuilder mainQuery = new BoolQueryBuilder()
.minimumShouldMatch(1)
.should(firstQuery).should(secondQuery);
SearchResponse response = client.prepareSearch("*")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(mainQuery)
.setFrom(0).setSize(60)
.get();
System.out.println(response.getHits().getTotalHits());
// on shutdown
client.close();
}
}
以下是应该出现在输出/控制台中的内容:
2 hits
让我知道这是否有帮助!