gpt4 book ai didi

java - 使用java highlevelrestclient从elasticsearch查询数据

转载 作者:行者123 更新时间:2023-12-01 17:30:16 25 4
gpt4 key购买 nike

如何根据实际对象中存在的属性从elasticsearch查询数据。

elsticsearch中存储的数据格式:

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

在 postman 中搜索查询:

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

这将在 postman 中返回所需的结果。

如何使用 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 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()

通过在项目中创建配置文件并在需要时 Autowiring 客户端,可以在 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;

}

关于java - 使用java highlevelrestclient从elasticsearch查询数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61135725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com