Elasticsearch count 查询,Elasticsearch 查询是否存在

1、Elasticsearch Count查询

当咱们使用  Elasticsearch  的时候,若是只想知道符合条件的结果集,应该怎么查询?html

更多教程点击:  Elasticsearch教程  。
java

1.1 Elasticsearch count Java API 查询

 
  1. Client client = ESTools.client; SearchResponse response = client.prepareSearch(MappingManager.ASK) .setTypes(MappingManager.ASK) .setQuery(new TermQueryBuilder("id", id))//设置查询类型 .setSearchType(SearchType.COUNT)//设置查询类型,有的版本可能过时 .setSize(0)//设置返回结果集为0 .get(); long length = response.getHits().totalHits();

最后返回了符合结果集的Count 数量,可是不返回结果集,不反回结果集靠size = 0  来决定,固然我以为  Elasticsearch  在一些版本里应该会对数据级别的Count 查询应该有更好的优化,本身对应想当前版本的  API  。个人Version:2.0.2 。json

1.2 Elasticsearch count Http API 查询

 
  1. POST - http://192.168.0.1:9200/index/type/_search/
  2. {
  3. "size" : 0,
  4. "query" : {
  5. "term" : {
  6. "id" : "adf183208e9a4116353e9d9cd78f2b6a"
  7. }
  8. }
  9. }



1.3 Elasticsearch Index Count查询

 
  1. CountResponse response = client.prepareCount("index1","index2").get();
  2. long count = response.getCount();//返回当前index Count数量

1.4 Elasticsearch Type Count查询

 
  1. CountResponse response = client.prepareCount("index1","index2").setTypes("type1","type2").get();
  2. long count = response.getCount();//返回符合条件的数据

2、Elasticsearch 查询数据是否存在

我也是认为  Elasticsearch  一些版本会有这个方法。下面看看官方的介绍:https://www.elastic.co/guide/en/elasticsearch/reference/2.3/search-exists.html 
api

2.1 curl 方式查询数据是否存在:

查询:

 
  1. $ curl -XGET 'http://localhost:9200/twitter/tweet/_search/exists?q=user:kimchy'
  2. $ curl -XGET 'http://localhost:9200/twitter/tweet/_search/exists' -d '
  3. {
  4. "query" : {
  5. "term" : { "user" : "kimchy" }
  6. }
  7. }'

返回结果:

 
  1. {
  2. "exists" : true
  3. }

  Java  API 我这个版本我没找到,其余版本有一些应该有 Java API 。app

2.2 Elasticsearch Java API 数据Exists判断。

 
  1. /**
  2. * 判断数据是否存在
  3. * @param id
  4. * @return
  5. */
  6. public static boolean existsById(String id){
  7. Client client = ESTools.client;
  8. SearchRequestBuilder searchBuilder = client.prepareSearch(MappingManager.ASK)
  9. .setTypes(MappingManager.ASK)
  10. .setQuery(new TermQueryBuilder("id", id))//设置查询类型
  11. .setSearchType(SearchType.COUNT)//设置查询类型,有的版本可能过时
  12. .setSize(0);//设置返回结果集为0
  13. SearchResponse response = searchBuilder.get();
  14. long length = response.getHits().totalHits();
  15. return length > 0;
  16. }

2.3 Elasticsearch Java API 判断 Index 是否存在。

 
  1. //Index 能够多个
  2. ExistsRequest request = new ExistsRequest("index1","index2");
  3. ExistsResponse response = client.exists(request).get();
  4. //返回是否存在
  5. boolean exists = response.exists();

2.4 Elasticsearch Java API 判断 Type 是否存在。

 
  1. //Index 能够多个
  2. ExistsRequest request = new ExistsRequest("index1","index2").types("type1","type2");
  3. ExistsResponse response = client.exists(request).get();
  4. //返回是否存在
  5. boolean exists = response.exists();