Spring 数据 Elasticsearch 按 JSON 结构查询
Spring Data Elasticsearch query by JSON structure
我正在使用 spring 数据 elasticsearch,当我使用 @Query 注释时,将代码与实际的 JSON elasticsearch 查询关联起来要容易得多,如中的示例所示此链接参考:
我想知道是否有一种方法可以通过 elasticsearch java 库通过完整的 JSON 主体进行查询而无需注释。 IE。在方法实现之类的东西中。这将帮助我解析响应中的突出显示等。
感谢您提供任何信息。
来自评论的澄清:我正在使用 spring-data-elasticsearch 3.0.10.RELEASE 和 Elasticsearch 6。因为 spring-data-elasticsearch 似乎不支持 RestHighLevelClient然而,我正在使用 TransportClient client = new PreBuiltTransportClient(elasticsearchSettings);创建 ElasticsearchTemplate 时的方法:return new ElasticsearchTemplate(client());
我找到了一种方法,但它需要您制作一个存在于 Elastic 节点上的脚本。参见 File-based scripts。它不是非常灵活,但试一试。这是要做的事情。
创建一个名为 template_doctype.mustache
的文件并将其复制到 $ELASTIC_HOME/config/scripts
。这是您可以根据需要定制的脚本。重启 Elastic 或等待 60 秒重新加载。
{
"query" : {
"match" : {
"type" : "{{param_type}}"
}
}
}
我的 pom.xml
依赖项:
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.0.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
(仅供参考,我使用 mvn dependency:tree
发现您的 spring-data-elasticsearch
版本隐式使用了 ElasticSearch 库的 5.5 版本,即使您使用的是 ElasticSearch 6。)
创建虚拟索引:
curl -X PUT http://localhost:9200/myindex
创建几个可用于匹配的文档以确保代码有效:
curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"foobar", "type":"book"}'
curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"fun", "type":"magazine"}'
尝试 运行 查询。此代码应 return 单个文件:
String clusterName = "my-application";
Settings elasticsearchSettings = Settings.builder().put("cluster.name", clusterName).build();
TransportClient client = new PreBuiltTransportClient(elasticsearchSettings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));
Map<String, Object> template_params = new HashMap<>();
// Here is where you put parameters to your script.
template_params.put("param_type", "book");
SearchResponse sr = new SearchTemplateRequestBuilder(client)
.setScript("template_doctype") // this is where you specify what template to use
.setScriptType(ScriptType.FILE)
.setScriptParams(template_params)
.setRequest(new SearchRequest())
.get()
.getResponse();
SearchHit[] results = sr.getHits().getHits();
for(SearchHit hit : results){
String sourceAsString = hit.getSourceAsString();
if (sourceAsString != null) {
Gson gson = new GsonBuilder().setPrettyPrinting()
.create();
Map map = gson.fromJson(sourceAsString, Map.class);
System.out.println( gson.toJson(map));
}
}
输出:
{
"title": "foobar",
"type": "book"
}
这是另一种方法,但不使用传输客户端。
将这些依赖项添加到您的 pom.xml
:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
<scope>compile</scope>
</dependency>
然后这样做:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
Client client = new Client();
final WebResource r = client.resource("http://localhost:9200").path("/myindex/_search");
String requestJson = "{\"query\" : {\"match\" : {\"type\" : \"book\"} }}";
ClientResponse response = r.post(ClientResponse.class, requestJson);
String json = response.getEntity(String.class);
Gson gson = new GsonBuilder().setPrettyPrinting()
.create();
Map map = gson.fromJson(json, Map.class);
System.out.println(gson.toJson(map));
// to convert to SearchResponse:
JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY,
new JsonFactory().createParser(json));
SearchResponse searchResponse = SearchResponse.fromXContent(xContentParser);
示例输出:
{
"took": 9.0,
"timed_out": false,
"_shards": {
"total": 5.0,
"successful": 5.0,
"failed": 0.0
},
"hits": {
"total": 1.0,
"max_score": 0.2876821,
"hits": [
{
"_index": "myindex",
"_type": "mydoc",
"_id": "AWXp8gZjXyu6lA_2Kpi2",
"_score": 0.2876821,
"_source": {
"title": "foobar",
"type": "book"
}
}
]
}
}
我正在使用 spring 数据 elasticsearch,当我使用 @Query 注释时,将代码与实际的 JSON elasticsearch 查询关联起来要容易得多,如中的示例所示此链接参考:
我想知道是否有一种方法可以通过 elasticsearch java 库通过完整的 JSON 主体进行查询而无需注释。 IE。在方法实现之类的东西中。这将帮助我解析响应中的突出显示等。
感谢您提供任何信息。
来自评论的澄清:我正在使用 spring-data-elasticsearch 3.0.10.RELEASE 和 Elasticsearch 6。因为 spring-data-elasticsearch 似乎不支持 RestHighLevelClient然而,我正在使用 TransportClient client = new PreBuiltTransportClient(elasticsearchSettings);创建 ElasticsearchTemplate 时的方法:return new ElasticsearchTemplate(client());
我找到了一种方法,但它需要您制作一个存在于 Elastic 节点上的脚本。参见 File-based scripts。它不是非常灵活,但试一试。这是要做的事情。
创建一个名为 template_doctype.mustache
的文件并将其复制到 $ELASTIC_HOME/config/scripts
。这是您可以根据需要定制的脚本。重启 Elastic 或等待 60 秒重新加载。
{
"query" : {
"match" : {
"type" : "{{param_type}}"
}
}
}
我的 pom.xml
依赖项:
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.0.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
(仅供参考,我使用 mvn dependency:tree
发现您的 spring-data-elasticsearch
版本隐式使用了 ElasticSearch 库的 5.5 版本,即使您使用的是 ElasticSearch 6。)
创建虚拟索引:
curl -X PUT http://localhost:9200/myindex
创建几个可用于匹配的文档以确保代码有效:
curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"foobar", "type":"book"}'
curl -X POST http://localhost:9200/myindex/mydoc -d '{"title":"fun", "type":"magazine"}'
尝试 运行 查询。此代码应 return 单个文件:
String clusterName = "my-application";
Settings elasticsearchSettings = Settings.builder().put("cluster.name", clusterName).build();
TransportClient client = new PreBuiltTransportClient(elasticsearchSettings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),9300));
Map<String, Object> template_params = new HashMap<>();
// Here is where you put parameters to your script.
template_params.put("param_type", "book");
SearchResponse sr = new SearchTemplateRequestBuilder(client)
.setScript("template_doctype") // this is where you specify what template to use
.setScriptType(ScriptType.FILE)
.setScriptParams(template_params)
.setRequest(new SearchRequest())
.get()
.getResponse();
SearchHit[] results = sr.getHits().getHits();
for(SearchHit hit : results){
String sourceAsString = hit.getSourceAsString();
if (sourceAsString != null) {
Gson gson = new GsonBuilder().setPrettyPrinting()
.create();
Map map = gson.fromJson(sourceAsString, Map.class);
System.out.println( gson.toJson(map));
}
}
输出:
{
"title": "foobar",
"type": "book"
}
这是另一种方法,但不使用传输客户端。
将这些依赖项添加到您的 pom.xml
:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
<scope>compile</scope>
</dependency>
然后这样做:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
Client client = new Client();
final WebResource r = client.resource("http://localhost:9200").path("/myindex/_search");
String requestJson = "{\"query\" : {\"match\" : {\"type\" : \"book\"} }}";
ClientResponse response = r.post(ClientResponse.class, requestJson);
String json = response.getEntity(String.class);
Gson gson = new GsonBuilder().setPrettyPrinting()
.create();
Map map = gson.fromJson(json, Map.class);
System.out.println(gson.toJson(map));
// to convert to SearchResponse:
JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY,
new JsonFactory().createParser(json));
SearchResponse searchResponse = SearchResponse.fromXContent(xContentParser);
示例输出:
{
"took": 9.0,
"timed_out": false,
"_shards": {
"total": 5.0,
"successful": 5.0,
"failed": 0.0
},
"hits": {
"total": 1.0,
"max_score": 0.2876821,
"hits": [
{
"_index": "myindex",
"_type": "mydoc",
"_id": "AWXp8gZjXyu6lA_2Kpi2",
"_score": 0.2876821,
"_source": {
"title": "foobar",
"type": "book"
}
}
]
}
}