Java代码对es多字段查询
时间: 2023-07-09 10:03:54 浏览: 141
以下是一个Java代码示例,用于在Elasticsearch中进行多字段查询:
```java
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
public class MultiFieldQueryExample {
public static void main(String[] args) {
String indexName = "my_index";
String typeName = "my_type";
String clusterName = "my_cluster";
String host = "localhost";
int port = 9300;
// Create a client
TransportClient client = new PreBuiltTransportClient(org.elasticsearch.common.settings.Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(new java.net.InetSocketAddress(host, port)));
// Query for multiple fields
List<String> fields = Arrays.asList("field1", "field2", "field3");
MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("search term", fields.toArray(new String[fields.size()]));
// Build the search request
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder);
searchSourceBuilder.from(0);
searchSourceBuilder.size(10);
// Execute the search
SearchResponse searchResponse = client.prepareSearch(indexName).setTypes(typeName).setSource(searchSourceBuilder).get();
// Process the search results
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
// Close the client
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用Elasticsearch的Java API来执行一个多字段查询。我们使用了`MultiMatchQueryBuilder`来创建查询,然后使用`SearchSourceBuilder`来构建搜索请求。最后,我们使用`TransportClient`来发送搜索请求,并处理结果。
阅读全文