Java Code Examples for org.elasticsearch.index.query.QueryBuilder

The following examples show how to use org.elasticsearch.index.query.QueryBuilder. These examples are extracted from open source projects. 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 Project: youkefu   Source File: QuickReplyRepositoryImpl.java    License: Apache License 2.0 7 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<QuickReply> getByCon(BoolQueryBuilder boolQueryBuilder, final int p , final int ps) {

	Page<QuickReply> pages  = null ;
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(QuickReply.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, QuickReply.class);
    }
    return pages ; 
}
 
Example 2
Source Project: fess   Source File: BsRoleCB.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SearchRequestBuilder build(SearchRequestBuilder builder) {
    if (_conditionQuery != null) {
        QueryBuilder queryBuilder = _conditionQuery.getQuery();
        if (queryBuilder != null) {
            builder.setQuery(queryBuilder);
        }
        _conditionQuery.getFieldSortBuilderList().forEach(sort -> {
            builder.addSort(sort);
        });
    }

    if (_conditionAggregation != null) {
        _conditionAggregation.getAggregationBuilderList().forEach(builder::addAggregation);
    }

    if (_specification != null) {
        builder.setFetchSource(_specification.columnList.toArray(new String[_specification.columnList.size()]), null);
    }

    return builder;
}
 
Example 3
@Test
public void getRangePredicateTest()
{
    logger.info("getRangePredicateTest - enter");

    constraintsMap.put("year", SortedRangeSet.copyOf(Types.MinorType.INT.getType(),
            ImmutableList.of(
                    Range.lessThan(allocator, Types.MinorType.INT.getType(), 1950),
                    Range.equal(allocator, Types.MinorType.INT.getType(), 1952),
                    Range.range(allocator, Types.MinorType.INT.getType(),
                            1955, false, 1972, true),
                    Range.equal(allocator, Types.MinorType.INT.getType(), 1996),
                    Range.greaterThanOrEqual(allocator, Types.MinorType.INT.getType(), 2010)),
            false));
    String expectedPredicate = "(_exists_:year) AND year:((<1950) OR (>1955 AND <=1972) OR (>=2010) OR 1952 OR 1996)";

    // Get the actual predicate and compare to the expected one.
    QueryBuilder builder = ElasticsearchQueryUtils.getQuery(constraintsMap);
    String actualPredicate = builder.queryName();

    logger.info("Predicates - Expected: {}, Actual: {}", expectedPredicate, actualPredicate);
    assertEquals("Predicates do not match", expectedPredicate, actualPredicate);

    logger.info("getRangePredicateTest - exit");
}
 
Example 4
@Override
public PagedResponse<Component> browseByPage(final CleanupPolicy policy,
                                             final Repository repository,
                                             final QueryOptions options)
{
  checkNotNull(options.getStart());
  checkNotNull(options.getLimit());

  StorageTx tx = UnitOfWork.currentTx();

  QueryBuilder query = convertPolicyToQuery(policy, options);

  log.debug("Searching for components to cleanup using policy {}", policy);

  SearchResponse searchResponse = invokeSearchByPage(policy, repository, options, query);

  List<Component> components = stream(searchResponse.getHits().spliterator(), false)
      .map(searchHit -> tx.findComponent(new DetachedEntityId(searchHit.getId())))
      .filter(Objects::nonNull)
      .collect(toList());

  return new PagedResponse<>(searchResponse.getHits().getTotalHits(), components);
}
 
Example 5
@Override
public List<ProfileThreadSnapshotRecord> queryRecords(String segmentId, int minSequence, int maxSequence) throws IOException {
    // search traces
    SearchSourceBuilder sourceBuilder = SearchSourceBuilder.searchSource();

    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    sourceBuilder.query(boolQueryBuilder);
    List<QueryBuilder> mustQueryList = boolQueryBuilder.must();

    mustQueryList.add(QueryBuilders.termQuery(ProfileThreadSnapshotRecord.SEGMENT_ID, segmentId));
    mustQueryList.add(QueryBuilders.rangeQuery(ProfileThreadSnapshotRecord.SEQUENCE).gte(minSequence).lt(maxSequence));
    sourceBuilder.size(maxSequence - minSequence);

    SearchResponse response = getClient().search(ProfileThreadSnapshotRecord.INDEX_NAME, sourceBuilder);

    List<ProfileThreadSnapshotRecord> result = new ArrayList<>(maxSequence - minSequence);
    for (SearchHit searchHit : response.getHits().getHits()) {
        ProfileThreadSnapshotRecord record = builder.map2Data(searchHit.getSourceAsMap());

        result.add(record);
    }
    return result;
}
 
Example 6
Source Project: youkefu   Source File: KbsTopicRepositoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<KbsTopic> getTopicByCon(BoolQueryBuilder boolQueryBuilder, final int p , final int ps) {

	Page<KbsTopic> pages  = null ;
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(KbsTopic.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class);
    }
    return pages ; 
}
 
Example 7
Source Project: metron   Source File: ElasticsearchSearchDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Defers to a provided {@link org.elasticsearch.index.query.QueryBuilder} for the query.
 * @param groupRequest The request defining the parameters of the grouping
 * @param queryBuilder The actual query to be run. Intended for if the SearchRequest requires wrapping
 * @return The results of the query
 * @throws InvalidSearchException When the query is malformed or the current state doesn't allow search
 */
protected GroupResponse group(GroupRequest groupRequest, QueryBuilder queryBuilder)
    throws InvalidSearchException {
  org.elasticsearch.action.search.SearchRequest esRequest;
  org.elasticsearch.action.search.SearchResponse esResponse;

  if (client == null) {
    throw new InvalidSearchException("Uninitialized Dao!  You must call init() prior to use.");
  }
  if (groupRequest.getGroups() == null || groupRequest.getGroups().size() == 0) {
    throw new InvalidSearchException("At least 1 group must be provided.");
  }

  esRequest = buildGroupRequest(groupRequest, queryBuilder);
  esResponse = requestSubmitter.submitSearch(esRequest);
  GroupResponse response = buildGroupResponse(groupRequest, esResponse);

  return response;
}
 
Example 8
Source Project: es-service-parent   Source File: EsQueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 前缀查询
 * 
 * @param boolQ
 * @param conditions
 * @param conditionType
 */
private void doPrefix(BoolQueryBuilder boolQ, List<Condition> conditions,
        ConditionType conditionType) {
    QueryBuilder prefix;
    BoolQueryBuilder subBoolQ;
    for (Condition condition : conditions) {
        if (condition.isSpaceSplit()) {
            subBoolQ = QueryBuilders.boolQuery();
            for (String word : KeyWordUtil.processKeyWord(condition.getValue())) {
                subBoolQ.should(QueryBuilders.prefixQuery(condition.getFiled(), word));
            }
            prefix = subBoolQ;
        } else {
            prefix = QueryBuilders.prefixQuery(condition.getFiled(), condition.getValue());
        }
        mergeBuilder(boolQ, prefix, conditionType);
    }
}
 
Example 9
public long runQuery(String name, int testNum, String index, long expectedHits, QueryBuilder query) {
    SearchResponse searchResponse = new CoordinateSearchRequestBuilder(client)
    .setIndices(index)
            .setQuery(query)
            .execute().actionGet();

    if (searchResponse.getFailedShards() > 0) {
        log("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
    }

    long hits = searchResponse.getHits().totalHits();
    if (hits != expectedHits) {
        log("[" + name + "][#" + testNum + "] Hits Mismatch:  expected [" + expectedHits + "], got [" + hits + "]");
    }

    return searchResponse.getTookInMillis();
}
 
Example 10
@Override
public QueryBuilder updateElasticsearchQuery(
    Graph graph,
    Elasticsearch5SearchIndex searchIndex,
    QueryBuilder query,
    QueryParameters queryParameters
) {
    List<String> fieldNames = getFieldNames(graph, searchIndex, queryParameters, getField());
    if (fieldNames == null) {
        return query;
    }

    HashMap<String, Object> scriptParams = new HashMap<>();
    scriptParams.put("hash", getHash());
    scriptParams.put("fieldNames", fieldNames);
    Script script = new Script(ScriptType.INLINE, "painless", scriptSrc, scriptParams);
    return QueryBuilders.functionScoreQuery(query, new ScriptScoreFunctionBuilder(script));
}
 
Example 11
Source Project: fess   Source File: BsFileConfigCB.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SearchRequestBuilder build(SearchRequestBuilder builder) {
    if (_conditionQuery != null) {
        QueryBuilder queryBuilder = _conditionQuery.getQuery();
        if (queryBuilder != null) {
            builder.setQuery(queryBuilder);
        }
        _conditionQuery.getFieldSortBuilderList().forEach(sort -> {
            builder.addSort(sort);
        });
    }

    if (_conditionAggregation != null) {
        _conditionAggregation.getAggregationBuilderList().forEach(builder::addAggregation);
    }

    if (_specification != null) {
        builder.setFetchSource(_specification.columnList.toArray(new String[_specification.columnList.size()]), null);
    }

    return builder;
}
 
Example 12
/**
 * Handle request for search.
 */
public Handler search() {
  return context -> {
    Payload payload = checkNotNull(context.getRequest().getPayload());
    try (InputStream is = payload.openInputStream()) {
      QueryBuilder query = parseSearchRequest(context.getRepository().getName(), is);
      List<PyPiSearchResult> results = new ArrayList<>();
      for (SearchHit hit : searchQueryService.browse(unrestricted(query))) {
        Map<String, Object> source = hit.getSource();
        Map<String, Object> formatAttributes = (Map<String, Object>) source.getOrDefault(
            MetadataNodeEntityAdapter.P_ATTRIBUTES, Collections.emptyMap());
        Map<String, Object> pypiAttributes = (Map<String, Object>) formatAttributes.getOrDefault(PyPiFormat.NAME,
            Collections.emptyMap());
        String name = Strings.nullToEmpty((String) pypiAttributes.get(PyPiAttributes.P_NAME));
        String version = Strings.nullToEmpty((String) pypiAttributes.get(PyPiAttributes.P_VERSION));
        String summary = Strings.nullToEmpty((String) pypiAttributes.get(PyPiAttributes.P_SUMMARY));
        results.add(new PyPiSearchResult(name, version, summary));
      }
      String response = buildSearchResponse(results);
      return HttpResponses.ok(new StringPayload(response, ContentTypes.APPLICATION_XML));
    }
  };
}
 
Example 13
Source Project: elasticsearch-sql   Source File: PrefixLikeQueryParser.java    License: MIT License 6 votes vote down vote up
@Override
public AtomicQuery parse(ElasticsearchParser.LikeClauseContext expression) {
    SqlConditionOperator operator = expression.not == null ? SqlConditionOperator.Like : SqlConditionOperator.NotLike;
    return parseCondition(expression, operator, null, (fieldName, operator1, rightParams) -> {
        String pattern = StringManager.removeStringSymbol(expression.pattern.getText());
        QueryBuilder prefixQuery = QueryBuilders.prefixQuery(fieldName, pattern);
        switch (operator1) {
            case Like: {
                return prefixQuery;
            }
            default:
            case NotLike: {
                return QueryBuilders.boolQuery().mustNot(prefixQuery);
            }
        }
    });
}
 
Example 14
Source Project: heroic   Source File: MetadataBackendKV.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AsyncFuture<CountSeries> countSeries(final CountSeries.Request filter) {
    return doto(c -> {
        final OptionalLimit limit = filter.getLimit();

        if (limit.isZero()) {
            return async.resolved(new CountSeries());
        }

        final QueryBuilder f = filter(filter.getFilter());

        SearchRequest request = c.getIndex().count(METADATA_TYPE);
        SearchSourceBuilder sourceBuilder = request.source();
        limit.asInteger().ifPresent(sourceBuilder::terminateAfter);
        sourceBuilder.query(new BoolQueryBuilder().must(f));

        final ResolvableFuture<SearchResponse> future = async.future();
        c.execute(request, bind(future));

        return future.directTransform(
            r -> new CountSeries(r.getHits().getTotalHits().value, false));

    });
}
 
Example 15
Source Project: SpringBootLearn   Source File: TestController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 正则查询
 * @return
 */
@GetMapping("/queryRegexpData")
public String queryRegexpData() {
    QueryBuilder queryBuilder = QueryBuilders.regexpQuery("name.keyword", "书名[0-9]{1,7}");
    List<Map<String, Object>> list = ElasticsearchUtil.searchListData(indexName, esType, queryBuilder, 10, null, null, null);
    return JSONObject.toJSONString(list);
}
 
Example 16
Source Project: fess   Source File: AdminSearchlistAction.java    License: Apache License 2.0 5 votes vote down vote up
@Execute
@Secured({ ROLE })
public HtmlResponse delete(final DeleteForm form) {
    validate(form, messages -> {}, this::asListHtml);
    verifyToken(this::asListHtml);
    final String docId = form.docId;
    try {
        final QueryBuilder query = QueryBuilders.termQuery(fessConfig.getIndexFieldDocId(), docId);
        fessEsClient.deleteByQuery(fessConfig.getIndexDocumentUpdateIndex(), query);
        saveInfo(messages -> messages.addSuccessDeleteDocFromIndex(GLOBAL));
    } catch (final Exception e) {
        throwValidationError(messages -> messages.addErrorsFailedToDeleteDocInAdmin(GLOBAL), this::asListHtml);
    }
    return asListHtml();
}
 
Example 17
@Test
void generateOneQueryRuleSearchOneFieldDateTime() throws ParseException {
  String value = "2015-05-22T06:12:13Z";
  Query<Entity> q = new QueryImpl<>().search(dateTimeAttrName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery = matchQuery(dateTimeAttrName, value);
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 18
@Override
public void testMustRewrite() throws IOException {
    QueryShardContext context = createShardContext();
    context.setAllowUnmappedFields(true);
    ExplorerQueryBuilder queryBuilder = createTestQueryBuilder();
    queryBuilder.boost(AbstractQueryBuilder.DEFAULT_BOOST);
    QueryBuilder rewritten = queryBuilder.rewrite(context);

    // though the query may be rewritten, we assert that we
    // always rewrite to an ExplorerQueryBuilder (same goes for ExplorerQuery...)
    assertThat(rewritten, instanceOf(ExplorerQueryBuilder.class));
    Query q = rewritten.toQuery(context);
    assertThat(q, instanceOf(ExplorerQuery.class));
}
 
Example 19
Source Project: heroic   Source File: MetadataBackendKV.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public QueryBuilder visitOr(final OrFilter or) {
    BoolQueryBuilder boolQuery = new BoolQueryBuilder();
    for (QueryBuilder qb : convertTerms(or.terms())) {
        boolQuery.should(qb);
    }
    boolQuery.minimumShouldMatch(1);
    return boolQuery;
}
 
Example 20
Source Project: fess   Source File: EsAbstractConditionQuery.java    License: Apache License 2.0 5 votes vote down vote up
public QueryBuilder getQuery() {
    if (queryBuilderList == null) {
        return null;
    } else if (queryBuilderList.size() == 1) {
        return queryBuilderList.get(0);
    }
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    queryBuilderList.forEach(query -> {
        boolQuery.must(query);
    });
    return boolQuery;
}
 
Example 21
Source Project: ProjectStudy   Source File: HighLevelRestController.java    License: MIT License 5 votes vote down vote up
/**
   * 列表查询
   *
   * @param page
* @param rows
* @param keyword
   * @return com.example.common.ResponseBean
   * @throws
   * @author wliduo[[email protected]]
   * @date 2019/8/15 16:01
   */
  @GetMapping("/book")
  public ResponseBean list(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer rows,
                           String keyword) throws IOException {
      SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
      // 分页采用简单的from + size分页,适用数据量小的,了解更多分页方式可自行查阅资料
      searchSourceBuilder.from((page - 1) * rows);
      searchSourceBuilder.size(rows);
      // 查询条件,只有查询关键字不为空才带查询条件
      if (StringUtils.isNoneBlank(keyword)) {
          QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "name", "desc");
          searchSourceBuilder.query(queryBuilder);
      }
      // 排序,根据ID倒叙
      searchSourceBuilder.sort("id", SortOrder.DESC);
      // SearchRequest
      SearchRequest searchRequest = new SearchRequest();
      searchRequest.source(searchSourceBuilder);
      // 查询ES
      SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
      SearchHits hits = searchResponse.getHits();
      // 获取总数
      Long total = hits.getTotalHits().value;
      // 遍历封装列表对象
      List<BookDto> bookDtoList = new ArrayList<>();
      SearchHit[] searchHits = hits.getHits();
      for (SearchHit searchHit : searchHits) {
          bookDtoList.add(JSON.parseObject(searchHit.getSourceAsString(), BookDto.class));
      }
      // 封装Map参数返回
      Map<String, Object> result = new HashMap<String, Object>(16);
      result.put("count", total);
      result.put("data", bookDtoList);
      return new ResponseBean(HttpStatus.OK.value(), "查询成功", result);
  }
 
Example 22
Source Project: youkefu   Source File: ESDataExchangeImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 批量删除,单次最大删除 10000条
 * @param query
 * @param index
 * @param type
 * @throws Exception
 */
public void deleteByCon(QueryBuilder query ,String type) throws Exception {
	BulkRequestBuilder bulkRequest = UKDataContext.getTemplet().getClient().prepareBulk();  
    SearchResponse response = UKDataContext.getTemplet().getClient().prepareSearch(UKDataContext.CALLOUT_INDEX).setTypes(type)  
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)  
            .setQuery(query)  
            .setFrom(0).setSize(10000).setExplain(true).execute().actionGet();  
    if(response.getHits().getTotalHits() > 0) {
	    for(SearchHit hit : response.getHits()){  
	        String id = hit.getId();  
	        bulkRequest.add(UKDataContext.getTemplet().getClient().prepareDelete(UKDataContext.CALLOUT_INDEX, type, id).request());  
	    }  
	    bulkRequest.get();  
    }
}
 
Example 23
Source Project: james-project   Source File: DeleteByQueryPerformer.java    License: Apache License 2.0 5 votes vote down vote up
private SearchRequest prepareSearch(QueryBuilder queryBuilder, RoutingKey routingKey) {
    return new SearchRequest(aliasName.getValue())
        .types(NodeMappingFactory.DEFAULT_MAPPING_NAME)
        .scroll(TIMEOUT)
        .source(searchSourceBuilder(queryBuilder))
        .routing(routingKey.asString());
}
 
Example 24
Source Project: youkefu   Source File: EkmKnowledgeTimesRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Page<EkmKnowledgeTimes> findByOrgi(String orgi, User user,
		List<String> ekmKnowledgeMasterid, Pageable pageable) {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	BoolQueryBuilder bq = QueryBuilders.boolQuery();
	if(user.isSuperuser() != true){
		if(ekmKnowledgeMasterid.size() > 0){
			for(String id : ekmKnowledgeMasterid){
				bq.should(termQuery("kbid" ,id)) ;
			}
		}else{
			bq.must(termQuery("kbid" ,UKDataContext.UKEFU_SYSTEM_NO_DAT)) ;
		}
	}
	boolQueryBuilder.must(bq) ;
	boolQueryBuilder.must(QueryBuilders.termQuery("orgi", orgi)) ;
	//过滤掉已过期的知识
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").to(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").from(new Date().getTime())) ;
	BoolQueryBuilder parentbq = QueryBuilders.boolQuery();
	parentbq.must(beginFilter) ;
	parentbq.must(endFilter) ;
	parentbq.must(QueryBuilders.termQuery("datastatus", false)) ;
	HasParentQueryBuilder hasParentQueryBuilder=QueryBuilders.hasParentQuery("uk_ekm_kb_master",parentbq);
	boolQueryBuilder.must(hasParentQueryBuilder) ;
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("viewtimes").unmappedType("long").order(SortOrder.DESC));
	searchQueryBuilder.withPageable(pageable) ;
	Page<EkmKnowledgeTimes> knowledgeTimesList = null ;
	if(elasticsearchTemplate.indexExists(EkmKnowledgeTimes.class)){
		knowledgeTimesList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , EkmKnowledgeTimes.class ) ;
    }
	
	return knowledgeTimesList;
}
 
Example 25
Source Project: elasticsearch-rest-command   Source File: AST_Search.java    License: The Unlicense 5 votes vote down vote up
private static QueryBuilder fromValueTypeQ(String field, String value, int valueType){
	if(value.contains("*") || value.contains("?")){
		if( value.length() > 1 && value.indexOf('*') == (value.length()-1))
			return QueryBuilders.prefixQuery(field, value.substring(0, value.length()-1));
		else
			return QueryBuilders.wildcardQuery(field, value);
	}else if(value.equalsIgnoreCase("")){
		
		return QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.boolFilter()
				.should(FilterBuilders.scriptFilter("doc['"+field+"'].value.size() == 0"))					
				.should(FilterBuilders.missingFilter(field).nullValue(true).existence(true)));
	}
	//全部使用对短语进行分词后再搜索
	return QueryBuilders.matchPhraseQuery(field, value);
	
	
	/*
	switch(valueType){
	
	case AST_TermExpression.TERM:
		return QueryBuilders.termQuery(field, value);
	case AST_TermExpression.PHRASE:			
		return QueryBuilders.matchPhraseQuery(field, value);
	}
	
	
	return null;
	*/
}
 
Example 26
@Override
protected Pair<SearchRequestBuilder, QueryBuilder> addSearchReferences(Pair<SearchRequestBuilder, QueryBuilder> builders,
                                                                       List<String> references) {
    BoolQueryBuilder query = (BoolQueryBuilder)builders.getRight();
    if (references.size() > 0){
        query = query.must(termsQuery(SearchService.FIELD_REFERENCE, references.toArray(new String[references.size()])));
    }
    return pairOf(builders.getLeft(), query);
}
 
Example 27
Source Project: molgenis   Source File: ClientFacade.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public Explanation explain(SearchHit searchHit, QueryBuilder query) {
  if (LOG.isTraceEnabled()) {
    LOG.trace(
        "Explaining doc with id '{}' in index '{}' for query '{}' ...",
        searchHit.getId(),
        searchHit.getIndex(),
        query);
  }

  String indexName = searchHit.getIndex();
  // FIXME: ClientFacade shouldn't assume that typename equals typename
  ExplainRequestBuilder explainRequestBuilder =
      client.prepareExplain(indexName, indexName, searchHit.getId()).setQuery(query);
  ExplainResponse explainResponse;
  try {
    explainResponse = explainRequestBuilder.get();
  } catch (ElasticsearchException e) {
    LOG.error("", e);
    throw new IndexException(
        format(
            "Error explaining doc with id '%s' in index '%s' for query '%s'.",
            searchHit.getId(), searchHit.getIndex(), query));
  }

  if (LOG.isDebugEnabled()) {
    LOG.debug(
        "Explained doc with id '{}' in index '{}' for query '{}'.",
        searchHit.getId(),
        searchHit.getIndex(),
        query);
  }
  return explainResponse.getExplanation();
}
 
Example 28
@Test
void generateOneQueryRuleNotEqualsTextNull() {
  String value = null;
  Query<Entity> q = new QueryImpl<>().not().eq(textAttrName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      boolQuery().mustNot(constantScoreQuery(boolQuery().mustNot(existsQuery(textAttrName))));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 29
Source Project: poseidon   Source File: ItemServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Page<EsItem> getByKey(String keyWord, int page, int limit) {
	Pageable pageable = PageRequest.of(page, limit);
	QueryBuilder queryBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("name", keyWord))
			.should(QueryBuilders.matchQuery("sellPoint", keyWord));
	NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
	nativeSearchQueryBuilder.withQuery(queryBuilder).withPageable(pageable)
			.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC));
	NativeSearchQuery query = nativeSearchQueryBuilder.build();
	LOGGER.info("DSL:{}", query.getQuery().toString());
	return elasticsearchTemplate.queryForPage(query, EsItem.class);
}
 
Example 30
@Test
void generateOneQueryRuleLikeHyperlink() {
  String value = "http://www.website.com/";
  Query<Entity> q = new QueryImpl<>().like(hyperlinkAttrName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      matchPhrasePrefixQuery(hyperlinkAttrName, value).slop(10).analyzer(DEFAULT_ANALYZER);
  assertQueryBuilderEquals(expectedQuery, query);
}