elasticsearch Java API 之Search API

此API是非常重要的,也是很有内涵的接口。用的好才是真的好。

列子一:

SearchResponse response = client.prepareSearch("index1", "index2") //同时查询索引index1\index2
        .setTypes("type1", "type2") //同时查询类型type1\type2
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
        .setQuery(QueryBuilders.termQuery("multi", "test"))             // Query
        .setPostFilter(FilterBuilders.rangeFilter("age").from(12).to(18))   // Filter
        .setFrom(0).setSize(60).setExplain(true)
        .execute()
        .actionGet();
//打印
print(reponse);

   解释结果:

public void print(SearchResponse response){ 
        SearchHits hits = response.getHits();
        SearchHit[] searchHists = hits.getHits();
        if (searchHists.length > 0) {
            for (SearchHit hit : searchHists) { 
                for(Map.Entry<String, SearchHitField> e : hit.fields().entrySet()){
                   System.out.println("fieldName="+e.getKey() +"\t  fieldValue="+ e.getValue().getValues());
                }  
                //高亮
                for(Map.Entry<String, HighlightField> e : hit.highlightFields().entrySet()){
                    StringBuilder highlight = new StringBuilder();
                    for(Text fragment : e.getValue().fragments()){
                        highlight.append(fragment).append("...");
                    }
                    System.out.println("fieldName="+e.getKey() +"\t fieldValue="+ highlight);
                }
            }
        }
    }

查整个集群时:

SearchResponse response = client.prepareSearch().execute().actionGet();

在JAVA中使用Scrolls

import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*;


QueryBuilder qb = termQuery("multi", "test");
SearchResponse scrollResp = client.prepareSearch(test)
        .setSearchType(SearchType.SCAN)
        .setScroll(new TimeValue(60000))
        .setQuery(qb).setSize(100).execute().actionGet(); 
        //100 hits per shard will be returned for each scroll//Scroll until no hits are returned
    while (true) { 
        for (SearchHit hit : scrollResp.getHits().getHits()) {
            //Handle the hit...
        }
        scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet();
        //Break condition: No hits are returned
        if (scrollResp.getHits().getHits().length == 0) {
            break;
        }
    }

MultiSearch API

SearchRequestBuilder srb1 = node.client()
    .prepareSearch().setQuery(QueryBuilders.queryString("elasticsearch")).setSize(1);
SearchRequestBuilder srb2 = node.client()
    .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);
MultiSearchResponse sr = node.client().prepareMultiSearch()
        .add(srb1)
        .add(srb2)
        .execute().actionGet();
// You will get all individual responses from MultiSearchResponse#getResponses()

long nbHits = 0;
for (MultiSearchResponse.Item item : sr.getResponses()) {
    SearchResponse response = item.getResponse();
    nbHits += response.getHits().getTotalHits();
}

Aggregations统计

SearchResponse sr = node.client().prepareSearch()
    .setQuery(QueryBuilders.matchAllQuery())
    .addAggregation(
            AggregationBuilders.terms("agg1").field("field")
    )
    .addAggregation(
            AggregationBuilders.dateHistogram("agg2")
                    .field("birth")
                    .interval(DateHistogram.Interval.YEAR)
    )
    .execute().actionGet();// Get your facet results
Terms agg1 = sr.getAggregations().get("agg1");
DateHistogram agg2 = sr.getAggregations().get("agg2");

使用查询模板(search Templates)

1、在config/scripts下添加模板。如:config/scripts/template_gender.mustache

{
    "template" : {
        "query" : {
            "match" : {
                "gender" : "{{param_gender}}"
            }
        }
    }}

2、在java程序中这样声明:

Map<String, Object> template_params = new HashMap<>();
template_params.put("param_gender", "male");

3、执行:

SearchResponse sr = client.prepareSearch()
        .setTemplateName("template_gender")
        .setTemplateType(ScriptService.ScriptType.FILE)
        .setTemplateParams(template_params)
        .get();

或者:

   A. 先存储.scripts文件

client.preparePutIndexedScript("mustache", "template_gender",
        "{\n" +
        "    \"template\" : {\n" +
        "        \"query\" : {\n" +
        "            \"match\" : {\n" +
        "                \"gender\" : \"{{param_gender}}\"\n" +
        "            }\n" +
        "        }\n" +
        "    }\n" +
        "}").get();

B.使用ScriptService.ScriptType.INDEXED声明来执行:

SearchResponse sr = client.prepareSearch()
        .setTemplateName("template_gender")
        .setTemplateType(ScriptService.ScriptType.INDEXED)
        .setTemplateParams(template_params)
        .get();


你可能感兴趣的:(elasticsearch Java API 之Search API)