多条件过滤查询:
TransportClient client = ElasticService.getTransportClient();
BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery(); // TODO 要匹配的字段修改 以及字段名称修改 boolBuilder = boolBuilder.should( QueryBuilders.matchQuery("title", keyWord)).should( QueryBuilders.matchQuery("videoTitle", keyWord)); List<String> mediaList = getChildMediaCode(sourceCode); boolBuilder = boolBuilder.must(QueryBuilders.termsQuery("sourceCode", mediaList));if (infoType != null && !"".equals(infoType)) {
boolBuilder = boolBuilder.must(QueryBuilders.matchQuery("infoType", infoType)); } // FilteredQueryBuilder query = null; Date startTime = null; Date endTime = null; if (start != null && !"".equals(start)) { startTime = DateUtil.strToDate(start); } if (end != null && !"".equals(end)) { endTime = DateUtil.strToDate(end); } // TODO 时间字段修改 BoolFilterBuilder filterBuilder = FilterBuilders.boolFilter().must( FilterBuilders.rangeFilter("createTime").from(startTime) .to(endTime));QueryBuilder query = QueryBuilders.filteredQuery(boolBuilder,
filterBuilder);// 页码
String pages = pageData.getString("currentPageNo"); int currentPageNo = 1; if (pages != null && !"".equals(pages)) { currentPageNo = Integer.parseInt(pages); } // 每页展示数量 Integer pageCount = Integer.parseInt(PropertiesUtils .getValueByKey("search.page")); int pageStart = (currentPageNo - 1) * pageCount; int pageEnd = currentPageNo * pageCount;SearchResponse response = client.prepareSearch()
.setIndices(PropertiesUtils.getValueByKey("elastic.index")) .setTypes(PropertiesUtils.getValueByKey("elastic.type")) .setQuery(query).setFrom(pageStart).setSize(pageEnd) .addSort("createTime", SortOrder.DESC).execute().actionGet(); SearchResponse res = client.prepareSearch() .setIndices(PropertiesUtils.getValueByKey("elastic.index")) .setTypes(PropertiesUtils.getValueByKey("elastic.type")) .setQuery(query).execute().actionGet(); client.close(); SearchHits result = response.getHits(); // 结果总数 long total = res.getHits().getTotalHits();