java从0到架构师

87_熟练掌握ES Java API_基于search temp

2020-03-04  本文已影响0人  小山居

<meta charset="utf-8">

87_熟练掌握ES Java API_基于search template实现按品牌分页查询模板

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

新建maven工程

image.png

page_query_by_brand.mustache

image.png

脚本内容,实现分页

{ "from": {{from}}, "size": {{size}}, "query": { "match": { "brand.keyword": "{{brand}}" } } }

利用java实现

SearchResponse sr = new SearchTemplateRequestBuilder(client)

.setScript("page_query_by_brand")

.setScriptType(ScriptService.ScriptType.FILE)

.setScriptParams(template_params)

.setRequest(new SearchRequest())

.get()

.getResponse();

源码如下


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<String, Object> scriptParams = new HashMap<String, Object>();
        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();
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读