Java Code Examples for org.elasticsearch.index.query.QueryBuilders#boolQuery()
The following examples show how to use
org.elasticsearch.index.query.QueryBuilders#boolQuery() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EkmKnowledgeRepositoryImpl.java From youkefu with Apache License 2.0 | 6 votes |
@Override public List<EkmKnowledge> findByKnowbaseidAndDatastatusAndOrgi(String knowbaseid, boolean datastatus, String orgi) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder bq = QueryBuilders.boolQuery() ; bq.must(QueryBuilders.termQuery("datastatus", datastatus)) ; bq.must(QueryBuilders.termQuery("orgi", orgi)) ; if(!StringUtils.isBlank(knowbaseid)){ bq.must(termQuery("knowbaseid" , knowbaseid)) ; }else{ bq.must(termQuery("knowbaseid" , UKDataContext.UKEFU_SYSTEM_NO_DAT)) ; } boolQueryBuilder.must(bq); NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ; Page<EkmKnowledge> knowledgeList = null ; if(elasticsearchTemplate.indexExists(EkmKnowledge.class)){ knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledge.class ) ; } return knowledgeList.getContent(); }
Example 2
Source File: TopologyQueryEsDAO.java From skywalking with Apache License 2.0 | 6 votes |
@Override public List<Call.CallDetail> loadEndpointRelation(long startTB, long endTB, String destEndpointId) throws IOException { SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource(); sourceBuilder.size(0); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.must() .add(QueryBuilders.rangeQuery(EndpointRelationServerSideMetrics.TIME_BUCKET).gte(startTB).lte(endTB)); BoolQueryBuilder serviceIdBoolQuery = QueryBuilders.boolQuery(); boolQuery.must().add(serviceIdBoolQuery); serviceIdBoolQuery.should() .add(QueryBuilders.termQuery( EndpointRelationServerSideMetrics.SOURCE_ENDPOINT, destEndpointId )); serviceIdBoolQuery.should() .add(QueryBuilders.termQuery( EndpointRelationServerSideMetrics.DEST_ENDPOINT, destEndpointId )); sourceBuilder.query(boolQuery); return loadEndpoint(sourceBuilder, EndpointRelationServerSideMetrics.INDEX_NAME, DetectPoint.SERVER); }
Example 3
Source File: EkmKnowledgeRepositoryImpl.java From youkefu with Apache License 2.0 | 6 votes |
@Override public EkmKnowledge findByIdAndOrgi(String id, String orgi) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder bq = QueryBuilders.boolQuery() ; bq.must(QueryBuilders.termQuery("id", id)) ; bq.must(QueryBuilders.termQuery("orgi", orgi)) ; boolQueryBuilder.must(bq); NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ; Page<EkmKnowledge> knowledgeList = null ; if(elasticsearchTemplate.indexExists(EkmKnowledge.class)){ knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledge.class ) ; } if (knowledgeList!=null && knowledgeList.getContent().size()>0) { return knowledgeList.getContent().get(0); }else { return null ; } }
Example 4
Source File: CustomerController.java From youkefu with Apache License 2.0 | 6 votes |
@RequestMapping("/personal") @Menu(type = "customer" , subtype = "personal") public ModelAndView personal(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ekind) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(termQuery("etype" , UKDataContext.CustomerTypeEnum.PERSONAL.toString())) ; if(!StringUtils.isBlank(ekind)){ boolQueryBuilder.must(termQuery("ekind" , ekind)) ; map.put("ekind", ekind) ; } if(!StringUtils.isBlank(q)){ map.put("q", q) ; } map.addAttribute("entCustomerList", entCustomerRes.findByCreaterAndSharesAndOrgi(super.getUser(request).getId(), super.getUser(request).getId(),super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ; return request(super.createAppsTempletResponse("/apps/business/customer/index")); }
Example 5
Source File: ElasticSearchCleanupComponentBrowseTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
private QueryBuilder getLastDownloadQuery(final String value) { BoolQueryBuilder neverDownloadDownloadBuilder = QueryBuilders.boolQuery(); neverDownloadDownloadBuilder.mustNot(existsQuery(LAST_DOWNLOADED_KEY)); neverDownloadDownloadBuilder.filter( rangeQuery(LAST_BLOB_UPDATED_KEY) .lte(format(NOW_MINUS_SECONDS, value)) ); RangeQueryBuilder lastDownloadRangeBuilder = rangeQuery(LAST_DOWNLOADED_KEY) .lte(format(NOW_MINUS_SECONDS, value)); BoolQueryBuilder lastDownloadShouldBuilder = QueryBuilders.boolQuery(); lastDownloadShouldBuilder.must(lastDownloadRangeBuilder); BoolQueryBuilder filterBuilder = QueryBuilders.boolQuery(); filterBuilder.should(lastDownloadShouldBuilder); filterBuilder.should(neverDownloadDownloadBuilder); return filterBuilder; }
Example 6
Source File: EkmKnowledgeRepositoryImpl.java From youkefu with Apache License 2.0 | 6 votes |
@Override public List<EkmKnowledge> findByCreaterAndDatastatusAndOrgi(String creater, boolean datastatus, String orgi) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder bq = QueryBuilders.boolQuery() ; bq.must(QueryBuilders.termQuery("creater", creater)) ; bq.must(QueryBuilders.termQuery("datastatus", datastatus)) ; bq.must(QueryBuilders.termQuery("orgi", orgi)) ; boolQueryBuilder.must(bq); NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ; Page<EkmKnowledge> knowledgeList = null ; if(elasticsearchTemplate.indexExists(EkmKnowledge.class)){ knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledge.class ) ; } return knowledgeList.getContent(); }
Example 7
Source File: ContactsController.java From youkefu with Apache License 2.0 | 6 votes |
@RequestMapping("/creater") @Menu(type = "customer" , subtype = "creater") public ModelAndView creater(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(termQuery("creater" , super.getUser(request).getId())) ; if(!StringUtils.isBlank(ckind)){ boolQueryBuilder.must(termQuery("ckind" , ckind)) ; map.put("ckind", ckind) ; } if(!StringUtils.isBlank(q)){ map.put("q", q) ; } map.addAttribute("contactsList", contactsRes.findByCreaterAndSharesAndOrgi(super.getUser(request).getId(), super.getUser(request).getId(),super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ; return request(super.createAppsTempletResponse("/apps/business/contacts/index")); }
Example 8
Source File: ContactsRepositoryImpl.java From youkefu with Apache License 2.0 | 5 votes |
@Override public Page<Contacts> findByDataAndOrgi(String orgi, String q, Pageable page) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(termQuery("datastatus" , false)) ; boolQueryBuilder.must(termQuery("orgi" ,orgi)) ; if(!StringUtils.isBlank(q)){ boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ; } return processQuery(boolQueryBuilder , page); }
Example 9
Source File: EkmKnowledgeRepositoryImpl.java From youkefu with Apache License 2.0 | 5 votes |
@Override public Page<EkmKnowledge> findByPubstatusAndDatastatusAndOrgiAndOwn( String pubstatus, boolean datastatus, String orgi, String own,User user, Pageable pageable) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder boolQueryBuilder1 = new BoolQueryBuilder(); boolQueryBuilder1.must(termQuery("pubstatus" , pubstatus)) ; boolQueryBuilder1.must(termQuery("datastatus" , datastatus)) ; boolQueryBuilder.must(boolQueryBuilder1) ; boolQueryBuilder.must(termQuery("orgi" ,orgi)) ; boolQueryBuilder.must(termQuery("own" ,own)) ; boolQueryBuilder.must(termQuery("creater" , user.getId())) ; return processQuery(boolQueryBuilder , pageable); }
Example 10
Source File: IndexerQueryBuilder.java From eplmp with Eclipse Public License 1.0 | 5 votes |
private void addAttributeToQueries(List<QueryBuilder> queries, String attributeName, List<SearchQuery.AbstractAttributeQuery> attributeList) { BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); boolQuery.must(QueryBuilders.nestedQuery(IndexerMapping.ATTRIBUTES_KEY, QueryBuilders.termQuery(IndexerMapping.ATTRIBUTES_KEY + "." + IndexerMapping.ATTRIBUTE_NAME, attributeName), ScoreMode.None)); List<NestedQueryBuilder> nestedQueries = new ArrayList<>(); BoolQueryBuilder valuesQuery = QueryBuilders.boolQuery(); for (SearchQuery.AbstractAttributeQuery attr : attributeList) { String attributeValue = attr.toString(); if (attributeValue != null && !attributeValue.isEmpty()) { nestedQueries.add(QueryBuilders.nestedQuery(IndexerMapping.ATTRIBUTES_KEY, QueryBuilders.termQuery(IndexerMapping.ATTRIBUTES_KEY + "." + IndexerMapping.ATTRIBUTE_VALUE, attributeValue), ScoreMode.None)); } } // Use 'should' on same attribute name, and 'must' for different attribute names // Only request for attribute name if no values // Use bool must if only one value passed // Compound should queries if many values (but must not be empty) if (!nestedQueries.isEmpty()) { if (nestedQueries.size() == 1) { boolQuery.must(nestedQueries.get(0)); } else { nestedQueries.forEach(valuesQuery::should); boolQuery.must(valuesQuery); boolQuery.mustNot(QueryBuilders.nestedQuery(IndexerMapping.ATTRIBUTES_KEY, QueryBuilders.termQuery(IndexerMapping.ATTRIBUTES_KEY + "." + IndexerMapping.ATTRIBUTE_VALUE, ""), ScoreMode.None)); } } queries.add(boolQuery); }
Example 11
Source File: EkmKnowledgeCollectRepositoryImpl.java From youkefu with Apache License 2.0 | 5 votes |
@Override public List<EkmKnowledgeCollect> findByCreaterAndStatusAndFolderidAndOrgi( String creater, String status, String folderid, String orgi) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder bq = QueryBuilders.boolQuery() ; bq.must(QueryBuilders.termQuery("creater", creater)) ; bq.must(QueryBuilders.termQuery("orgi", orgi)) ; bq.must(QueryBuilders.termQuery("status", status)) ; bq.must(QueryBuilders.termQuery("folderid", folderid)) ; boolQueryBuilder.must(bq); return this.proccessQuery(boolQueryBuilder); }
Example 12
Source File: EsQueryBuilder.java From es-service-parent with Apache License 2.0 | 5 votes |
/** * 模糊查询-支持带空格 * * @param boolQ * @param conditions * @param conditionType */ private void doFuzz(BoolQueryBuilder boolQ, List<Condition> conditions, ConditionType conditionType) { BoolQueryBuilder builder; String filed; for (Condition condition : conditions) { builder = QueryBuilders.boolQuery(); filed = condition.getFiled(); // 字段名为空则在_all上搜索 filed = StringUtils.isBlank(filed) ? "_all" : filed; if (condition.isSpaceSplit()) { for (String word : KeyWordUtil.processKeyWord(condition.getValue())) { // fuzziness 0.0到1.0,设置相似性.AUTO为自动 builder.should(QueryBuilders.matchPhrasePrefixQuery(filed, word) .fuzziness(org.elasticsearch.common.unit.Fuzziness.AUTO) .prefixLength(1)); // slop 1 builder.should(QueryBuilders.matchPhrasePrefixQuery(filed, word).slop(1)); // prefix builder.should(QueryBuilders.prefixQuery(filed, word)); } } else { // fuzziness 0.0到1.0,设置相似性.AUTO为自动 builder.should(QueryBuilders.matchPhrasePrefixQuery(filed, condition.getValue()) .fuzziness(org.elasticsearch.common.unit.Fuzziness.AUTO).prefixLength(1)); // slop 1 builder.should(QueryBuilders.matchPhrasePrefixQuery(filed, condition.getValue()) .slop(1)); // prefix builder.should(QueryBuilders.prefixQuery(filed, condition.getValue())); } // 合并 mergeBuilder(boolQ, builder, conditionType); } }
Example 13
Source File: QueryGenerator.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
private QueryBuilder createQueryClauseShould(QueryRule queryRule, EntityType entityType) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); for (QueryRule subQuery : queryRule.getNestedRules()) { boolQueryBuilder.should(createQueryClause(subQuery, entityType)); } return boolQueryBuilder; }
Example 14
Source File: ContactsController.java From youkefu with Apache License 2.0 | 5 votes |
@RequestMapping("/index") @Menu(type = "customer" , subtype = "index") public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if(!StringUtils.isBlank(q)){ map.put("q", q) ; } if(!StringUtils.isBlank(ckind)){ boolQueryBuilder.must(termQuery("ckind" , ckind)) ; map.put("ckind", ckind) ; } map.addAttribute("contactsList", contactsRes.findByCreaterAndSharesAndOrgi(super.getUser(request).getId(), super.getUser(request).getId(),super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ; return request(super.createAppsTempletResponse("/apps/business/contacts/index")); }
Example 15
Source File: MetadataQueryEsDAO.java From skywalking with Apache License 2.0 | 5 votes |
@Override public List<Service> getAllBrowserServices(long startTimestamp, long endTimestamp) throws IOException { SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must().add(QueryBuilders.termQuery(ServiceTraffic.NODE_TYPE, NodeType.Browser.value())); sourceBuilder.query(boolQueryBuilder); sourceBuilder.size(queryMaxSize); SearchResponse response = getClient().search(ServiceTraffic.INDEX_NAME, sourceBuilder); return buildServices(response); }
Example 16
Source File: ElasticsearchSearchVertexQuery.java From vertexium with Apache License 2.0 | 5 votes |
private QueryBuilder orFilters(List<QueryBuilder> filters) { if (filters.size() == 1) { return filters.get(0); } else { BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); for (QueryBuilder filter : filters) { boolQuery.should(filter); } boolQuery.minimumShouldMatch(1); return boolQuery; } }
Example 17
Source File: QuickReplyRepositoryImpl.java From youkefu with Apache License 2.0 | 5 votes |
@Override public void deleteByCate(String cate ,String orgi) { DeleteQuery deleteQuery = new DeleteQuery(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(termQuery("orgi" , orgi)) ; boolQueryBuilder.must(termQuery("cate" , cate)) ; deleteQuery.setQuery(boolQueryBuilder); elasticsearchTemplate.delete(deleteQuery); }
Example 18
Source File: SearchServiceImpl.java From emotional_analysis with Apache License 2.0 | 4 votes |
@Override public PageBean<Map<String,Object>> getSearchResult(int page, int rows,String content) throws Exception { PageBean<Map<String, Object>> searchListPageBean = new PageBean<Map<String, Object>>(); BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery(); boolBuilder.must(QueryBuilders.matchQuery("content", content)); PageHelper.startPage(page, rows); SearchRequestBuilder searchRequestBuilder = ESClientUtils.getClient().prepareSearch("hotcomments") .setTypes("logs").setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(boolBuilder).setFrom(page).setSize(3); long totalHits = ESClientUtils.getClient().prepareSearch("hotcomments").setTypes("logs") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(boolBuilder).get().getHits().getTotalHits(); searchRequestBuilder.setHighlighterPostTags("</span>"); searchRequestBuilder.setHighlighterPreTags("<span style=\"color:red\">"); searchRequestBuilder.addHighlightedField("content"); // 执行结果 SearchResponse response = searchRequestBuilder.get(); // 接受结果 List<Map<String, Object>> result = new ArrayList<>(); // 遍历结果 for (SearchHit hit : response.getHits()) { Map<String, Object> source = hit.getSource(); String songName = null; String songUrl = null; Set<Entry<String, Object>> entrySet = source.entrySet(); for (Entry<String, Object> entry : entrySet) { if (entry.getKey().equals("songId")) { Integer songId = (Integer) entry.getValue(); songName = SearchUtils.getSongNameById(songId); songUrl = SearchUtils.getSongUrlById(songId); } } source.put("songName", songName); source.put("songUrl", songUrl); // 处理高亮片段 Map<String, HighlightField> highlightFields = hit.getHighlightFields(); HighlightField nameField = highlightFields.get("content"); if (nameField != null) { Text[] fragments = nameField.fragments(); String nameTmp = ""; for (Text text : fragments) { nameTmp += text; } // 将高亮片段组装到结果中去 source.put("content", nameTmp); } result.add(source); } long totalPage = (totalHits + 3 - 1) / 3; if(page > totalPage){ page = 1; } searchListPageBean.setPage(page); searchListPageBean.setTotalPage(totalPage); searchListPageBean.setList(result); return searchListPageBean; }
Example 19
Source File: TasteSearchRestAction.java From elasticsearch-taste with Apache License 2.0 | 4 votes |
@Override protected void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { final Info info = new Info(request); final String systemId = request.param("systemId"); if (StringUtils.isBlank(systemId)) { onError(channel, new NotFoundException("No system_id.")); return; } final String[] systemIds = systemId.trim().split(","); if (systemIds.length == 0) { onError(channel, new NotFoundException("No system_id.")); return; } if (info.getIdIndex() == null) { onError(channel, new NotFoundException("No search type.")); return; } final OnResponseListener<SearchResponse> responseListener = searchResponse -> { final SearchHits hits = searchResponse.getHits(); if (hits.totalHits() == 0) { onError(channel, new NotFoundException("No " + info.getIdField() + " data for " + systemId + " in " + info.getIdIndex() + "/" + info.getIdType())); return; } final SearchHit[] searchHits = hits.getHits(); final long[] targetIds = new long[hits.getHits().length]; for (int i = 0; i < targetIds.length && i < searchHits.length; i++) { final SearchHit hit = searchHits[i]; final SearchHitField field = hit.field(info.getIdField()); final Number targetId = field.getValue(); if (targetId != null) { targetIds[i] = targetId.longValue(); } } if (targetIds.length == 0) { onError(channel, new NotFoundException("No " + info.getIdField() + " for " + systemId + " in " + info.getIdIndex() + "/" + info.getIdType())); return; } doSearchRequest(request, channel, client, info, targetIds); }; final BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); for (final String id : systemIds) { boolQueryBuilder.should(QueryBuilders.termQuery("system_id", id)); } boolQueryBuilder.minimumNumberShouldMatch(1); client.prepareSearch(info.getIdIndex()).setTypes(info.getIdType()) .setQuery(boolQueryBuilder).addField(info.getIdField()) .addSort(info.getTimestampField(), SortOrder.DESC) .setSize(systemIds.length) .execute(on(responseListener, t -> onError(channel, t))); }
Example 20
Source File: SearchServiceImpl.java From dk-fitting with Apache License 2.0 | 4 votes |
/** *根据多条件组合与查询 (相当于sql里的and,age=32 and gender=m,也可以单个条件查询age=32. ) * @param hostIp ES集群的IP地址 * @param port 连接ES集群的端口号 * @param clusterName ES集群的名称 * @param indexName ES集群的索引 * @param typeName ES集群的类型名称 * @param filed 查询的字段名称 比如:age,gender * @param filedName 查询的内容 比如:32,m * @param start 记录偏移 , null-默认为0 * @param size 记录偏移 , null-默认为10 * @return * @throws TException */ @Override public Map<String, String> MustSearch(String hostIp, int port, String clusterName, String indexName, String typeName, String filed, String filedName, int start, int size) throws TException { Client client=null; try { client = ESUtils.getClient( hostIp, port, clusterName ); } catch (Exception e) { e.printStackTrace(); } BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); int start2 = (Integer)start == null ? 0 : start; int size2 = (Integer)size == null ? 10 : size; //String field="age,gender"; //String Type="32,m"; if (filed.contains( "," )||filedName.contains( "," )){ String[] split = filed.split( "," ); String[] split1= filedName.split( "," ); for (int i = 0; i <split.length ; i++) { boolQueryBuilder.must( QueryBuilders.termsQuery( split[i], split1[i]) ); } }else { boolQueryBuilder.must( QueryBuilders.termsQuery( filed, filedName ) ); } String[] index; if (indexName.contains( "," )){ index = indexName.split( "," ); }else { index = new String[]{indexName}; } String[] type; if (typeName.contains( "," )){ type = typeName.split( "," ); }else { type = new String[]{typeName}; } SearchResponse response = client.prepareSearch( index ).setTypes( type ) .setQuery( boolQueryBuilder ).setFrom( start2 ).setSize( size2 ).get(); SearchHit[] hits1 = response.getHits().getHits(); Map<String,String> map=new LinkedHashMap<>( ); long totalHits =0; for (SearchHit searchHit: hits1) { String s = JSON.toJSONString( searchHit.getSource(), SerializerFeature.PrettyFormat ); totalHits++; map.put( String.valueOf(totalHits ),s ); } long totalHits1 = response.getHits().totalHits; map.put( "count",String.valueOf( totalHits1 ) ); return map; }