我想出了一种方法来做到这一点,但它需要您制作一个位于 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 版本隐式使用了 5.5 版本的 ElasticSearch 库,即使您使用的是 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"}'
尝试运行查询。此代码应返回单个文档:
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"
}