elasticsearch做爲開源的搜索引擎,支持複雜的搜索,本文示例用java客戶端實現的搜索。java
一、maven引入依賴jar包緩存
<dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>1.1.0</version> </dependency>
二、產生clientelasticsearch
Settings settings = ImmutableSettings.settingsBuilder() .put("client.transport.sniff", true) .build(); TransportClient client = new TransportClient(settings);
三、使用query查詢maven
SearchResponse actionGet = client.prepareSearch("indexName") .setTypes("typeName") .setQuery( QueryBuilders.boolQuery().must(QueryBuilders.termQuery("attr1", "value1")) ).execute().actionGet(); SearchHits hits = actionGet.getHits(); List<Map<String, Object>> matchRsult = new LinkedList<Map<String, Object>>(); for (SearchHit hit : hits.getHits()) { matchRsult.add(hit.getSource()); }
查詢條件有好多種形式,均可以經過QueryBuilders來構建組合:ui
QueryBuilders.inQuery("attr1", new String[{"value1","value2","value3"}); QueryBuilders.rangeQuery("attr1").gt("value1")//gt lt eq gte lte;
查詢的形式和意思均可以根據方法名猜想的出來。搜索引擎
四、使用filter查詢code
filter和query的使用方式相似,它是使用FilterBuilders來構建查詢條件。
不過比query多了or、and關係查詢xml
FilterBuilders.orFilter(FilterBuilders.termFilter("attr1", "value1"),FilterBuilders.termFilter("attr2", "value2")); FilterBuilders.andFilter(FilterBuilders.termFilter("attr1", "value1"),FilterBuilders.termFilter("attr2", "value2"));
是經過 .setPostFilter(filter) 指定給search;
五、分頁查詢
一種方式是指定from/size索引
SearchResponse actionGet = elasticClient.prepareSearch("indexName") .setTypes("typeName") .setQuery( QueryBuilders.boolQuery().must(QueryBuilders.termQuery("attr1", "value1")) ) .setFrom(100) .setSize(200) .execute().actionGet();
另一種是使用Scroll/size,若是結果超過size大小,會返回size條記錄,並返回一個scrollId,能夠用這個scrollId繼續往下查詢。get
第一次查詢
SearchResponse actionGet = elasticClient.prepareSearch("indexName") .setTypes("typeName") .setQuery( QueryBuilders.boolQuery().must(QueryBuilders.termQuery("attr1", "value1")) ) .setScroll(new TimeValue(60000)) .setSize(200) .execute().actionGet(); String scrollId = actionGet.getScrollId();
後面的查詢
SearchResponse actionGet = elasticClient.prepareSearchScroll(actionGet.getScrollId()) .setScroll(new TimeValue(600000)) .execute().actionGet();
第二種分頁查詢必須在設定的緩存時間內往下查詢,並且一旦進行了查詢就必須往下繼續查,不能回頭重複查詢。