英文:
How to use ElasticSearch JSON DSL in Java?
问题
我正在开发一个Spring Boot项目,在使用Elasticsearch时遇到了一些问题。
用户将一些以JSON格式表示的Elasticsearch DSL查询字符串放入数据库中,而我对这些字符串一无所知。我需要做的是获取这些查询字符串并将它们用于在Elasticsearch中搜索信息。
在Python中,DSL可以作为参数,如下所示:
body = {
"query":{
"match_all":{}
}
}
es.search(index="my_index", doc_type="test_type", body=body)
在Java中,如何在不了解字符串细节的情况下执行搜索,只使用JSON格式的查询呢?
英文:
I'm working on a springboot project and having some trouble with ElasticSearch.
The user will put some JSON-format elasticsearch DSL query strings in the database and they are black-box to me. What I need to do is get the query strings and use them so search information in elasticsearch.
In python, the DSL can be a parameter like this:
body = {
"query":{
"match_all":{}
}
}
es.search(index="my_index",doc_type="test_type",body=body)
How can I perform the search without knowing the details of the string and just using the JSON format query in Java?
答案1
得分: 0
我相信在现代的ES客户端库中有两种方法可以实现。虽然我自己没有尝试过,但第一种方法似乎相当简单。
第一种方法是使用低级别客户端:
Request request = new Request("POST", "/index/_search");
request.setJsonEntity(jsonString);
Response response = client.performRequest(request);
看起来只需将JSON作为字符串推送到setJsonEntity中,就可以完成设置了。
第二种方法是使用高级别客户端,尽管它可能会变得复杂,但可以提供更强大的API。你可能知道,Elasticsearch有XContent的概念,它可以在不同格式(包括JSON)之间进行序列化/反序列化。从理论上讲,可以创建JsonXContentParser,然后可以用它来实例化SearchSourceBuilder:
SearchSourceBuilder.fromXContent(jsonXContentParser);
问题只在于JsonXContentParser需要一些参数来实例化,而我不太确定如何正确地创建这些依赖项。
英文:
I believe there are two ways to do it in modern ES client libraries. I haven't tried them myself, but first one seems to be pretty straightforward.
First one is using low-level client:
Request request = new Request("POST", "/index/_search");
request.setJsonEntity(jsonString);
Response response = client.performRequest(request);
Seems like it's enough just to push JSON as string into setJsonEntity, and you're already set.
Second one is to use high level client, and this gets tricky, though it can provide more robust API. As you might know, elasticsearch has concept of XContent, which is serialization/deserialization to/from different formats, including JSON. Theoretically, it is possible to create JsonXContentParser, which then can be used to instantiate SearchSourceBuilder:
SearchSourceBuilder.fromXContent(jsonXContentParser);
The problem is only that JsonXContentParser requires number of arguments to be instantiated, and i'm not sure how to properly create those dependencies.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论