ES Java API_基于search template实现按品牌分页查询模板

2018-02-27 11:53:23来源:oschina作者:jxlgzwh人点击

分享

搜索模板的功能,java api怎么去调用一个搜索模板


page_query_by_brand.mustache


{


"from": {{from}},


"size": {{size}},


"query": {


"match": {


"brand.keyword": "{{brand}}"


}


}


}

SearchResponse sr = new SearchTemplateRequestBuilder(client)


.setScript("page_query_by_brand")


.setScriptType(ScriptService.ScriptType.FILE)


.setScriptParams(template_params)


.setRequest(new SearchRequest())


.get()


.getResponse();

package com.roncoo.es.senior;


import java.net.InetAddress;


import java.util.HashMap;


import java.util.Map;


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.script.ScriptType;


import org.elasticsearch.script.mustache.SearchTemplateRequestBuilder;


import org.elasticsearch.search.SearchHit;


import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class SearchTemplatePageQuery {


@SuppressWarnings({ "resource", "unchecked" })


public static void main(String[] args) throws Exception {


Settings settings = Settings.builder()


.put("cluster.name", "elasticsearch")


.build();


TransportClient client = new PreBuiltTransportClient(settings)


.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));


Map 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();


}


}

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台