美文网首页java从0到架构师
87_熟练掌握ES Java API_基于search temp

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

作者: 小山居 | 来源:发表于2020-03-04 18:05 被阅读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();
    }
    
}

相关文章

网友评论

    本文标题:87_熟练掌握ES Java API_基于search temp

    本文链接:https://www.haomeiwen.com/subject/zbiblhtx.html