es的config/scripts目录下,预先保存搜索模板,后缀名是.mustache,文件名是page_query_by_brand
{
"from": {{from}},
"size": {{size}},
"query": {
"match": {
"brand.keyword": "{{brand}}"
}
}
}
在
《 Elasticsearch 之(36)使用search template将搜索模板化》篇幅中,详细讲解了模版的创建和保存。
在进行 条件 search template 查询
package com.es.app;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.script.mustache.SearchTemplateRequestBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
public class SearchTemplatePageQueryApp {
public static void main(String[] args) throws Exception {
Settings settings = Settings.builder()
.put("cluster.name", "elasticsearch")
.put("client.transport.sniff", true)
.build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("from", 0);
scriptParams.put("size", 1);
scriptParams.put("brand", "宝马");
SearchResponse searchResponse = new SearchTemplateRequestBuilder(client)
.setScript("page_query_by_brand")
.setScriptType(ScriptType.FILE)
.setScriptParams(scriptParams)
.setRequest(new SearchRequest("car_shop").types("sales"))
.get()
.getResponse();
for(SearchHit searchHit : searchResponse.getHits().getHits()) {
System.out.println(searchHit.getSourceAsString());
}
client.close();
}
}