首页 > 解决方案 > 使用 java highlevelrestclient 从 elasticsearch 查询数据

问题描述

如何根据实际对象内部存在的属性从弹性搜索中查询数据。

elsticsearch中存储的数据格式:

{
  "principals": [
    {
      "id": 1,
      "account": {
        "account_id": 2
      }
    }
  ]
}

在邮递员中搜索查询:

{
  "query": {
    "terms": {
      "account_id": [
        1
      ]
    }
  }
}

这是在邮递员中返回所需的结果。

如何使用 highlevelrestclient 在 java 中实现相同的功能。

标签: javaamazon-web-servicesspring-bootelasticsearchelasticsearch-high-level-restclient

解决方案


我不确定您的上述搜索查询在获取相应文档时是如何工作的。

但是我已经通过这种方式索引并搜索了您的文档:

映射:

{
  "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 Resthighlevelclient 搜索查询

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()

通过在项目中创建配置文件并在需要时自动装配客户端,可以在 spring-boot 应用程序中实例化 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;

    }

推荐阅读