Java Code Examples for org.elasticsearch.index.query.BoolQueryBuilder#must()

The following examples show how to use org.elasticsearch.index.query.BoolQueryBuilder#must() . 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: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 7 votes vote down vote up
@Override
public List<QuickReply> getQuickReplyByOrgi(String orgi , String cate,String type, String q) {
	
	List<QuickReply> list  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	
	if(!StringUtils.isBlank(cate)){
		boolQueryBuilder.must(termQuery("cate" , cate)) ;
	}
	if(!StringUtils.isBlank(type)){
		boolQueryBuilder.must(termQuery("type" , type)) ;
	}
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(0, 10000));
	if(elasticsearchTemplate.indexExists(QuickReply.class)){
		list = elasticsearchTemplate.queryForList(searchQuery, QuickReply.class);
    }
    return list ; 
}
 
Example 2
Source File: BaseDaoESImp.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
@Override
public BoolQueryBuilder createAndQueryForSingleValue(List<TargetingChannel> tcs)
{
    BoolQueryBuilder boolQueryBuilder = null;
    for (TargetingChannel tc : tcs)
    {
        if (boolQueryBuilder == null)
        {
            boolQueryBuilder = createQueryForSingleValues(tc);
        }
        else
        {
            BoolQueryBuilder boolQueryBuilder1 = createQueryForSingleValues(tc);
            boolQueryBuilder.must(boolQueryBuilder1);
        }
    }
    return boolQueryBuilder;
}
 
Example 3
Source File: ElasticSearchUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
private static BoolQueryBuilder getBoolQueryBuilder(QueryLogicType logicType, List<QueryBuilder> queryBuilders) {
    BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    for (QueryBuilder queryBuilder : queryBuilders) {

        switch (logicType) {
            case AND:
                boolQueryBuilder.must(queryBuilder);
                break;
            case OR:
                boolQueryBuilder.should(queryBuilder);
                break;
            case NOT:
                boolQueryBuilder.mustNot(queryBuilder);
                break;
            default:
                break;
        }
    }
    return boolQueryBuilder;
}
 
Example 4
Source File: EkmKnowledgeMasterRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<EkmKnowledgeMaster> findByOrgiAndDatastatus(String orgi, boolean datastatus) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("datastatus", datastatus)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(new PageRequest(0, 100000)) ;
	Page<EkmKnowledgeMaster> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeMaster.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeMaster.class ) ;
    }
	
	return knowledgeList.getContent();
}
 
Example 5
Source File: CustomerController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/expsearch")
@Menu(type = "customer" , subtype = "customer")
public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response , @Valid String q , @Valid String ekind) throws IOException {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	if(!StringUtils.isBlank(q)){
    	map.put("q", q) ;
    }
	if(!StringUtils.isBlank(ekind)){
		boolQueryBuilder.must(termQuery("ekind" , ekind)) ;
    	map.put("ekind", ekind) ;
    }
	
	Iterable<EntCustomer> 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)));
	MetadataTable table = metadataRes.findByTablename("uk_entcustomer") ;
	List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
	for(EntCustomer customer : entCustomerList){
		values.add(UKTools.transBean2Map(customer)) ;
	}

	response.setHeader("content-disposition", "attachment;filename=UCKeFu-EntCustomer-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  

	ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
	excelProcess.process();
	
    return ;
}
 
Example 6
Source File: EkmKnowledgeTimesRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<EkmKnowledgeTimes> findByKbidAndVersionAndOrgi(String kbid,
		int version, String orgi) {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("kbid", kbid)) ;
	bq.must(QueryBuilders.termQuery("version", version)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder) ;
	Page<EkmKnowledgeTimes> knowledgeTimesList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeTimes.class)){
		knowledgeTimesList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeTimes.class ) ;
    }
	
	return knowledgeTimesList.getContent();
}
 
Example 7
Source File: EkmKnowledgeMasterRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public List<EkmKnowledgeMaster> findByOrgi(String orgi) {

	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	boolQueryBuilder.must(bq); 
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withPageable(new PageRequest(0, 100000)) ;
	Page<EkmKnowledgeMaster> knowledgeList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeMaster.class)){
		knowledgeList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeMaster.class ) ;
    }
	
	return knowledgeList.getContent();
}
 
Example 8
Source File: EntCustomerRepositoryImpl.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@Override
public Page<EntCustomer> findByCreaterAndSharesAndOrgi(String creater, String shares ,String orgi, boolean includeDeleteData ,String q , Pageable page) {
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder boolQueryBuilder1 = new BoolQueryBuilder();
	boolQueryBuilder1.should(termQuery("creater" , creater)) ;
	boolQueryBuilder1.should(termQuery("shares" , creater)) ;
	boolQueryBuilder1.should(termQuery("shares" , "all")) ;
	boolQueryBuilder.must(boolQueryBuilder1) ;
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	if(includeDeleteData){
		boolQueryBuilder.must(termQuery("datastatus" , true)) ;
	}else{
		boolQueryBuilder.must(termQuery("datastatus" , false)) ;
	}
	if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	return processQuery(boolQueryBuilder , page);
}
 
Example 9
Source File: BaseElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected Pair<SearchRequestBuilder, QueryBuilder> addSearchTerms(Pair<SearchRequestBuilder, QueryBuilder> builders,
                                                                  String searchTerms) {
    BoolQueryBuilder query = (BoolQueryBuilder)builders.getRight();

    if (searchTerms.contains(":")) {
        String[] termWithType = searchTerms.split(":");
        String termType = termWithType[0];
        String termValue = termWithType[1];
        // little fragile but seems like most providers follow this convention, there isn't a nice way to get the type
        // without a handle to a reference.
        query = query.must(termQuery(SearchService.FIELD_TYPE, "sakai:" + termType));
        query = query.must(matchQuery(SearchService.FIELD_CONTENTS, termValue));
    } else {
        query = query.must(simpleQueryStringQuery(searchTerms));
    }

    return pairOf(builders.getLeft(), query);
}
 
Example 10
Source File: IndexerQueryBuilder.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
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: EsSearchRequest.java    From mall with Apache License 2.0 5 votes vote down vote up
/**
 * 添加产品名称搜索
 *
 * @param boolQueryBuilder bool 查询
 */
private void addNameQuery(BoolQueryBuilder boolQueryBuilder) {
    if (StringUtils.isEmpty(this.queryString)) {
        return;
    }

    boolQueryBuilder.must(QueryBuilders.matchQuery("spuName", this.queryString));
}
 
Example 12
Source File: ElasticSearchHelper.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
/**
 * This method returns termQuery if any present in List provided
 *
 * @param key for search in termquery
 * @param val value of the key to be searched
 * @param query which will be updated according to key , value and constraints
 * @param constraintsMap for setting any constraints on values for the specified key
 * @return BoolQueryBuilder
 */
private static BoolQueryBuilder getTermQueryFromList(
    Object val, String key, BoolQueryBuilder query, Map<String, Float> constraintsMap) {
  if (!((List) val).isEmpty()) {
    if (((List) val).get(0) instanceof String) {
      ((List<String>) val).replaceAll(String::toLowerCase);
      query.must(createTermsQuery(key + RAW_APPEND, (List<String>) val, constraintsMap.get(key)));
    } else {
      query.must(createTermsQuery(key, (List) val, constraintsMap.get(key)));
    }
  }
  return query;
}
 
Example 13
Source File: BoolApiMain.java    From elasticsearch-pool with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
        RestHighLevelClient client = HighLevelClient.getInstance();
        try{
            BoolQueryBuilder matchQueryBuilder = QueryBuilders.boolQuery();
            matchQueryBuilder.must(QueryBuilders.termQuery("cpname","llbxinterface"));
            matchQueryBuilder.mustNot(QueryBuilders.termQuery("status","fail"));
            matchQueryBuilder.should(QueryBuilders.rangeQuery("utm").from(0,true).to(100,true));
            matchQueryBuilder.minimumShouldMatch(1);
//            matchQueryBuilder.filter();

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(matchQueryBuilder);
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(3);

            SearchRequest searchRequest = new SearchRequest("serverlog_20180701");//限定index
            searchRequest.types("log");//限定type
            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest);
            System.out.println(searchResponse);


        }finally{
            HighLevelClient.close();
        }
    }
 
Example 14
Source File: EkmKnowledgeCollectRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@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 15
Source File: EkmKnowledgeCollectRepositoryImpl.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@Override
public List<EkmKnowledgeCollect> findByStatusAndCreaterAndOrgi(
		String status, String creater, String orgi) {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery() ; 
	bq.must(QueryBuilders.termQuery("status", status)) ;
	bq.must(QueryBuilders.termQuery("orgi", orgi)) ;
	bq.must(QueryBuilders.termQuery("creater", creater)) ;
	boolQueryBuilder.must(bq); 
	HasParentQueryBuilder hasParentQueryBuilder=QueryBuilders.hasParentQuery("uk_ekm_kb_master",QueryBuilders.termQuery("datastatus", false));
	boolQueryBuilder.must(hasParentQueryBuilder) ;
	
	return this.proccessQuery(boolQueryBuilder);
}
 
Example 16
Source File: BookService.java    From demo-project with MIT License 5 votes vote down vote up
/**
 * 根据关键词搜索某用户下的书
 *
 * @param content 关键词
 */
@GetMapping("/search")
public List<Book> searchByUserIdAndName(int userId, String content) {
    BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    boolQueryBuilder.must(QueryBuilders.termQuery("userId", userId));
    boolQueryBuilder.must(QueryBuilders.matchQuery("name", content));
    SearchSourceBuilder builder = new SearchSourceBuilder();
    builder.size(10).query(boolQueryBuilder);
    return esUtil.search(EsUtil.INDEX_NAME, builder, Book.class);

}
 
Example 17
Source File: ElasticSearchFinder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void processNamedAssociationContainsNameSpecification( BoolQueryBuilder queryBuilder,
                                                               NamedAssociationContainsNamePredicate<?> spec,
                                                               Map<String, Object> variables )
{
    LOGGER.trace( "Processing NamedAssociationContainsNameSpecification {}", spec );
    String name = spec.namedAssociation().toString() + "._named";
    Object value = resolveVariable( spec.name(), variables );
    queryBuilder.must( termQuery( name, value ) );
}
 
Example 18
Source File: ElasticSearchService.java    From SpringMVC-Project with MIT License 4 votes vote down vote up
/**
     * 查询文章数据
     */
    public List<Article> queryArticle(String keyword, String category) throws IOException {
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //数据偏移量,下标从0开始,取前5个
        sourceBuilder.from(0);
        sourceBuilder.size(5);
        //指定返回结果的字段,第一个参数为包含的字段,第二个参数为排除的字段
        sourceBuilder.fetchSource(new String[]{"title"}, new String[]{});

        //分词匹配查询

        //且条件组合,必须满足每一项,计算相关性得分
        boolBuilder.must(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.must(QueryBuilders.matchQuery("content", keyword));

        //且条件组合,必须满足每一项,不计算相关性得分
//        boolBuilder.filter(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.filter(QueryBuilders.matchQuery("content", keyword));

        //或条件组合,满足任意一项即可
//        boolBuilder.should(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.should(QueryBuilders.matchQuery("content", keyword));

        //非条件组合,不满足每一项
//        boolBuilder.mustNot(QueryBuilders.matchQuery("title", keyword));
//        boolBuilder.mustNot(QueryBuilders.matchQuery("content", keyword));

        if (StringUtils.isNotBlank(category)) {
            //不分词匹配查询
            boolBuilder.must(QueryBuilders.matchPhraseQuery("category", category));

            //只匹配分词,如字段值为"Quick Foxes",则只有"Quick"和"Foxes"可以匹配到值,"Quick Foxes"则不行
//            boolBuilder.must(QueryBuilders.termQuery("category", category));
        }

        //范围条件
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime");
        rangeQueryBuilder.gte("2018-12-31T00:00:00Z");
        rangeQueryBuilder.lte("2018-12-31T23:59:59Z");
        boolBuilder.must(rangeQueryBuilder);

        sourceBuilder.query(boolBuilder);
        SearchRequest searchRequest = new SearchRequest();
        //指定索引名称,如果未指定,则会查询所有
        searchRequest.indices(BLOG_INDEX);
        searchRequest.types(ARTICLE_TYPE);
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        logger.info("查询数据 | {} | {} | {}", keyword, category, JSON.toJSONString(searchResponse));

        List<Article> articleList = Lists.newArrayList();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            Article article = new Article();
            article.setId(Long.valueOf(searchHit.getId()));
            article.setTitle((String) searchHit.getSourceAsMap().get("title"));

            articleList.add(article);
        }

        return articleList;
    }
 
Example 19
Source File: PolicyElasticRepository.java    From micronaut-microservices-poc with Apache License 2.0 4 votes vote down vote up
public PolicyDocument findByNumber(String number) {
    SearchRequest searchRequest = new SearchRequest("policy_stats")
            .types("policy_type");

    BoolQueryBuilder filterBuilder = QueryBuilders.boolQuery();

    filterBuilder.must(QueryBuilders.termQuery("number.keyword", number));

    SearchSourceBuilder srcBuilder = new SearchSourceBuilder()
            .query(filterBuilder)
            .size(10);

    searchRequest.source(srcBuilder);

    SearchResponse searchResponse = executeSearch(searchRequest);

    SearchHit[] hits = searchResponse.getHits().getHits();

    return hits.length > 0
            ? jsonConverter.objectFromString(hits[0].getSourceAsString(), PolicyDocument.class)
            : null;
}
 
Example 20
Source File: NugetTagsSearchContribution.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void contribute(final BoolQueryBuilder query, final String type, final String value) {
  if (value != null) {
    query.must(QueryBuilders.matchQuery(type, value));
  }
}