1. 程式人生 > >【ElasticSearch實戰】——ES常用查詢條件與mysql對比

【ElasticSearch實戰】——ES常用查詢條件與mysql對比

類比mysql,我們需要=、>、>=、<、<= 、or、and、in、like、count、sum、group by、order by、limit 

在高版本的ES裡面使用了boolquery替換了filter

1、等於號=

  1. QueryBuilders.termQuery("isDel",1));

  2. //termQuery相當於=,相當於isDel=1

2、大於小於號

  1. QueryBuilders.rangeQuery("overdueStartTime").lte(startDate.getTime())

  2. //rangeQuery

  3. //lte <=

  4. //lt <

  5. //gte >=

  6. //gt >

3、or、and

  1. boolQueryBuilder.must(QueryBuilders.termQuery("isDel",req.getIs_del()));

  2. //must相當於and

  3. caseStatusQuery.should(QueryBuilders.termQuery("caseStatus",s));

  4. //should相當於or

4、in

  1. QueryBuilders.termsQuery("clientCompanyId",req.getClientCompanyIdList())

  2. //termQuery相當於in,可以傳遞list

5、like

  1. QueryBuilders.wildcardQuery("phone1", "*" + req.getTelephone() + "*")

  2. //wildcard 正則匹配

  3. QueryBuilders.matchPhraseQuery("debtorName", req.getDebtor_name())

  4. //matchPhrase 不會分詞,直接匹配有完整相關短語的記錄

6、sum&&count

  1. AggregationBuilder debtTotalSum = AggregationBuilders.sum(DEBT_TOTAL_SUM_KEY).field("debtTotal");

  2. AggregationBuilder debtTotalCount = AggregationBuilders.count(DEBT_TOTAL_COUNT_KEY).field("debtTotal");

7、order by and limit

  1. SearchResponse searchResponse = client.prepareSearch(ElasticSearchUtil.getIndexName())

  2. .setTypes(ElasticSearchUtil.TYPE_NAME)

  3. .setQuery(boolQueryBuilder)

  4. //指定查詢欄位

  5. .addStoredField("id")

  6. .addSort(order, sortOrder)

  7. //分頁

  8. .setFrom((currentPage - 1) * limit).setSize(limit)

  9. .execute()

  10. .actionGet();

8、批量插入

  1. public void batchInsert(List<CaseTable> list,Client client) {

  2. LOGGER.info("---------案件批量插入索引開始--------");

  3. BulkRequestBuilder bulkRequest = client.prepareBulk();

  4. long start = System.currentTimeMillis();

  5. BulkRequestBuilder delRequest = client.prepareBulk();

  6. for (CaseTable caseTable :list){

  7. IndexRequestBuilder ir = client.prepareIndex()

  8. .setIndex(ElasticSearchUtil.INDEX_NAME_CASE)

  9. .setType(ElasticSearchUtil.TYPE_NAME_CASE)

  10. .setId(caseTable.getId().toString())

  11. .setSource(JSON.toJSONString(caseTable));

  12. bulkRequest.add(ir);

  13. start = System.currentTimeMillis();

  14. BulkResponse bulkResponse = bulkRequest.execute().actionGet();

  15. LOGGER.info("案件批量插入迴圈所用時間 search time:{}ms", System.currentTimeMillis() - start);

  16. if (!bulkResponse.hasFailures()) {

  17. LOGGER.info("----------案件批量插入成功一輪------------");

  18. }

  19. }