我想出了一个方法,但它需要你做一个脚本,生活在弹性节点。看到了吗
File-based scripts
创建一个名为
template_doctype.mustache
并将其复制到
$ELASTIC_HOME/config/scripts
{
"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"}'
尝试运行查询。此代码应返回单个文档:
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"
}