如何根据实际对象内部的属性从elasticsearch查询数据。
elsticsearch中存储的数据格式:
{
"principals": [
{
"id": 1,
"account": {
"account_id": 2
}
}
]
}
在邮递员中搜索查询:
{
"query": {
"terms": {
"account_id": [
1
]
}
}
}
这是在邮递员中返回所需的结果。
如何使用highlevelrestclient在java中实现同样的功能。
我不确定您上面的搜索查询是如何获取相应文档的。
但我已经通过这种方式索引和搜索了您的文档:
映射:
{
"mappings": {
"properties": {
"principals": {
"properties": {
"id": { "type": "integer" },
"account": {
"properties": {
"account_id": { "type": "integer" }
}
}
}
}
}
}
}
搜索查询:
{
"query": {
"terms": {
"principals.account.account_id": [2]
}
}
}
搜索结果:
"hits": [
{
"_index": "nestedindex",
"_type": "_doc",
"_id": "2",
"_score": 1.0,
"_source": {
"principals": [
{
"id": 1,
"account": {
"account_id": 2
}
}
]
}
}
]
通过Elasticsearch Resthighlevel客户端搜索查询
SearchRequest searchRequest = new SearchRequest("testIndex"); //in place of "testIndex" you can give your index name
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
List<Integer> accountIds = new ArrayList<Integer>();
accountIds.add(2);
sourceBuilder.query(QueryBuilders.termsQuery("principals.account.account_id", accountIds));
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse =
client.search(searchRequest, RequestOptions.DEFAULT); //client is ES client
return searchResponse; //you can read your hits through searchResponse.getHits().getHits()
ElasticSearch客户端可以在春季启动应用程序中实例化,方法是在项目中创建配置文件,并在需要时自动连接客户端:
@Configuration
@Primary
public class ElasticsearchConfig {
private RestHighLevelClient restHighLevelClient;
@Bean(destroyMethod = "close")
public RestHighLevelClient client() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
return client;
}