java - 使用 java highlevelrestclient 从 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 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;
}
推荐阅读
- c++ - 基于输入的各种类型的 C++ 模板
- javascript - 如何使用 javascript 函数打开 API url,如何将变量从 html 传输到 ts 文件
- r - 针对不同类别运行多个卡方检验
- asp.net-core - System.Security.Authentication.AuthenticationException:系统错误
- azure-devops - 如果上一个阶段在 Azure Pipeline Release 中有错误,则跳过一个阶段
- r - 使用提取函数从R中的栅格中提取像素值时维护SpatialPolygonDataFrame列?
- javascript - Firebase 函数从外部 API 调用返回错误文本
- c++ - 合并排序相同的输出 C++
- html - 如何在滚动时停止图片移动,CSS背景位置:固定;
- javascript - 开玩笑:ReferenceError:未定义描述