Java Code Examples for org.elasticsearch.index.query.QueryBuilders#matchAllQuery()

The following examples show how to use org.elasticsearch.index.query.QueryBuilders#matchAllQuery() . 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: TransportAddFeatureToSetAction.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
private void fetchFeaturesFromStore() {
    SearchRequest srequest = new SearchRequest(store);
    srequest.setParentTask(clusterService.localNode().getId(), task.getId());
    QueryBuilder nameQuery;

    if (featureNamesQuery.endsWith("*")) {
        String parsed = featureNamesQuery.replaceAll("[*]+$", "");
        if (parsed.isEmpty()) {
            nameQuery = QueryBuilders.matchAllQuery();
        } else {
            nameQuery = QueryBuilders.matchQuery("name.prefix", parsed);
        }
    } else {
        nameQuery = QueryBuilders.matchQuery("name", featureNamesQuery);
    }
    BoolQueryBuilder bq = QueryBuilders.boolQuery();
    bq.must(nameQuery);
    bq.must(QueryBuilders.matchQuery("type", StoredFeature.TYPE));
    srequest.types(IndexFeatureStore.ES_TYPE);
    srequest.source().query(bq);
    srequest.source().fetchSource(true);
    srequest.source().size(StoredFeatureSet.MAX_FEATURES);
    searchAction.execute(srequest, wrap(this::onSearchResponse, this::onSearchFailure));
}
 
Example 2
Source File: QueryAllMain.java    From elasticsearch-pool with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    RestHighLevelClient client = HighLevelClient.getInstance();
    try{
        QueryBuilder matchQueryBuilder = QueryBuilders.matchAllQuery();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(matchQueryBuilder);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(5);

        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 3
Source File: ElasticsearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Iterable<? extends DocumentResult> geoRelationQuery(String relation, IRI geoProperty, Shape shape,
		Var contextVar) throws MalformedQueryException, IOException {
	ShapeRelation spatialOp = toSpatialOp(relation);
	if (spatialOp == null) {
		return null;
	}
	final String fieldName = toGeoShapeFieldName(SearchFields.getPropertyField(geoProperty));
	GeoShapeQueryBuilder fb = QueryBuilders.geoShapeQuery(fieldName,
			ElasticsearchSpatialSupport.getSpatialSupport().toShapeBuilder(shape));
	fb.relation(spatialOp);
	QueryBuilder qb = QueryBuilders.matchAllQuery();
	if (contextVar != null) {
		qb = addContextTerm(qb, (Resource) contextVar.getValue());
	}

	SearchRequestBuilder request = client.prepareSearch();
	SearchHits hits = search(request, QueryBuilders.boolQuery().must(qb).filter(fb));
	return Iterables.transform(hits, new Function<SearchHit, DocumentResult>() {

		@Override
		public DocumentResult apply(SearchHit hit) {
			return new ElasticsearchDocumentResult(hit, geoContextMapper);
		}
	});
}
 
Example 4
Source File: TestElasticSearchDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
private SearchResponse search(String indexName, String structuredQuery, int start,
    int size, String freeTextQuery, String docType) throws ParserException {
    QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
    if (StringUtils.isNotEmpty(structuredQuery)) {
        Expression expression = Expression.fromString(structuredQuery);
        queryBuilder = expression.getFilterBuilder();
    }

    BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
    QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
    BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
    final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(indexName)
        .setQuery(fq)
        .setTypes(docType)
        .storedFields("_id")
        .setFrom(start)
        .setSize(size);

    return srb.get();
}
 
Example 5
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
private SearchResult<String> searchObjectIdsViaExpression(String structuredQuery, int start, int size, List<String> sortOptions, String freeTextQuery, String docType) {
    try {
        // Build query
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        if(StringUtils.isNotEmpty(structuredQuery)) {
            Expression expression = Expression.fromString(structuredQuery);
            queryBuilder = expression.getFilterBuilder();
        }

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
        BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);

        return searchObjectIds(indexName, fq, start, size, sortOptions, docType);
    } catch (Exception e) {
        throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, e.getMessage(), e);
    }
}
 
Example 6
Source File: ElasticsearchQueryUtils.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * Given a set of Constraints, create the query that can push predicates into the Elasticsearch data-source.
 * @param constraintSummary is a map containing the constraints used to form the predicate for predicate push-down.
 * @return the query builder that will be injected into the query.
 */
protected static QueryBuilder getQuery(Map<String, ValueSet> constraintSummary)
{
    List<String> predicates = new ArrayList<>();

    constraintSummary.forEach((fieldName, constraint) -> {
        String predicate = getPredicate(fieldName, constraint);
        if (!predicate.isEmpty()) {
            // predicate1, predicate2, predicate3...
            predicates.add(predicate);
        }
    });

    if (predicates.isEmpty()) {
        // No predicates formed.
        logger.info("Predicates are NOT formed.");
        return QueryBuilders.matchAllQuery();
    }

    // predicate1 AND predicate2 AND predicate3...
    String formedPredicates = Strings.collectionToDelimitedString(predicates, AND_OPER);
    logger.info("Formed Predicates: {}", formedPredicates);

    return QueryBuilders.queryStringQuery(formedPredicates).queryName(formedPredicates);
}
 
Example 7
Source File: MatchAllQueryDemo.java    From elasticsearch-full with Apache License 2.0 5 votes vote down vote up
@Test
public void testForClient() throws Exception {
    QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
    SearchResponse searchResponse = client.prepareSearch()
            .setIndices("indexName")
            .setTypes("typeName")
            .setQuery(queryBuilder)
            .execute().actionGet();
}
 
Example 8
Source File: ProductQueryServiceImpl.java    From elasticsearch-tutorial with MIT License 5 votes vote down vote up
protected QueryBuilder getQueryBuilder(SearchCriteria searchCriteria)
{
    QueryBuilder matchQueryBuilder = null;
    
    String queryString = searchCriteria.getQuery();
    
    if (StringUtils.isBlank(queryString))
    {
        matchQueryBuilder = QueryBuilders.matchAllQuery();
    } 
    else
    {
        final String filterSpecialCharsQueryString = escapeQueryChars(queryString);
        final QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryString(filterSpecialCharsQueryString);

        // Add fields
        queryStringQueryBuilder.field(SearchDocumentFieldName.TITLE.getFieldName(), (float) 0.5)
                                .field(SearchDocumentFieldName.DESCRIPTION.getFieldName(), (float) 0.15)
                                ;
        
        for (final String contentCategoryFieldName : SearchFacetName.categoryFacetFields)
        {
            queryStringQueryBuilder.field(SearchDocumentFieldName.CATEGORIES_ARRAY.getFieldName() + "."
                    + contentCategoryFieldName, 1);
        }
        
        matchQueryBuilder = queryStringQueryBuilder;
    }
    
    if(searchCriteria.isUseBoostingFactor())
    {
        FunctionScoreQueryBuilder queryBuilder = new FunctionScoreQueryBuilder(matchQueryBuilder);
        ScoreFunctionBuilder scoreFunctionBuilder = new ScriptScoreFunctionBuilder().script(SearchDocumentFieldName
                .getCalculatedScoreScriptForBostFactor());
        queryBuilder.add(scoreFunctionBuilder);
        return queryBuilder;
    }

    return matchQueryBuilder;
}
 
Example 9
Source File: ProductQueryServiceImpl.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
protected QueryBuilder getQueryBuilder(final SearchCriteria searchCriteria) {
	QueryBuilder matchQueryBuilder = null;
	final String queryString = searchCriteria.getQuery();
	if (StringUtils.isBlank(queryString)) {
		matchQueryBuilder = QueryBuilders.matchAllQuery();
	} else {
		final String filterSpecialCharsQueryString = escapeQueryChars(queryString);
		final QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders
				.queryString(filterSpecialCharsQueryString);
		// Add fields
		queryStringQueryBuilder.field(
				SearchDocumentFieldName.TITLE.getFieldName(), (float) 0.5)
				.field(SearchDocumentFieldName.DESCRIPTION.getFieldName(),
						(float) 0.15);
		for (final String contentCategoryFieldName : SearchFacetName.categoryFacetFields) {
			queryStringQueryBuilder.field(
					SearchDocumentFieldName.CATEGORIES_ARRAY.getFieldName()
							+ "." + contentCategoryFieldName, 1);
		}
		matchQueryBuilder = queryStringQueryBuilder;
	}
	if (searchCriteria.isUseBoostingFactor()) {
		final FunctionScoreQueryBuilder queryBuilder = new FunctionScoreQueryBuilder(
				matchQueryBuilder);
		final ScoreFunctionBuilder scoreFunctionBuilder = new ScriptScoreFunctionBuilder()
				.script(SearchDocumentFieldName
						.getCalculatedScoreScriptForBostFactor());
		queryBuilder.add(scoreFunctionBuilder);
		return queryBuilder;
	}
	return matchQueryBuilder;
}
 
Example 10
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
private SearchResult<String> search(String indexName, String structuredQuery, int start, int size,
    List<String> sortOptions, String freeTextQuery, String docType) {
    try {
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        if (StringUtils.isNotEmpty(structuredQuery)) {
            Expression expression = Expression.fromString(structuredQuery);
            queryBuilder = expression.getFilterBuilder();
        }

        BoolQueryBuilder filterQuery = QueryBuilders.boolQuery().must(queryBuilder);
        QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery(freeTextQuery);
        BoolQueryBuilder fq = QueryBuilders.boolQuery().must(stringQuery).must(filterQuery);
        final SearchRequestBuilder srb = elasticSearchClient.prepareSearch(indexName)
                .setQuery(fq)
                .setTypes(docType)
                .storedFields("_id")
                .setFrom(start)
                .setSize(size);

        if (sortOptions != null) {
            sortOptions.forEach(sortOption -> addSortOptionToSearchRequest(srb, sortOption));
        }

        SearchResponse response = srb.get();

        LinkedList<String> result = StreamSupport.stream(response.getHits().spliterator(), false)
                .map(SearchHit::getId)
                .collect(Collectors.toCollection(LinkedList::new));
        long count = response.getHits().getTotalHits();

        return new SearchResult<>(count, result);
    } catch (ParserException e) {
        String errorMsg = String.format("Error performing search on index:%s with docType:%s", indexName, docType);
        logger.error(errorMsg);
        throw new ApplicationException(Code.BACKEND_ERROR, errorMsg, e);
    }
}
 
Example 11
Source File: Queries.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
/**
     * construct the only query used by all
     *
     * @param query
     * @return
     */
    private static QueryBuilder queryBuilder(String query) {


        //return QueryBuilders.queryStringQuery(query).defaultOperator(QueryStringQueryBuilder.Operator.AND);

        if (StringUtils.isEmpty(query)) {
            return QueryBuilders.matchAllQuery();
        }

//        return QueryBuilders.multiMatchQuery(query)
//            .operator(MatchQueryBuilder.Operator.AND)
//            .field("name^3")
//            .field("content").field("path").field("version").field("project")
//            ;

        return QueryBuilders.queryStringQuery(query)
            .allowLeadingWildcard(true)
            .defaultOperator(QueryStringQueryBuilder.Operator.AND)
            .field("name^3")
            .field("content").field("path").field("version").field("project").field("extension")

            ;

        //QueryBuilders.queryStringQuery(query)
        //.defaultOperator(QueryStringQueryBuilder.Operator.AND)
        //TODO : attention, si on souhaite que la recherche s'effectue bien sur l'ensemble des champs
        //il faut veuillez à ce qu'il soit tous présent ici
        //en cas d'ajout, penser à les ajouter ici
        //.field("content")



      /*  return QueryBuilders.boolQuery()
            .should(QueryBuilders.termQuery("content", query))
            .should(
                QueryBuilders.queryStringQuery(query)
                    .defaultOperator(QueryStringQueryBuilder.Operator.AND)
            );*/
    }
 
Example 12
Source File: QueryHelper.java    From fess with Apache License 2.0 5 votes vote down vote up
protected QueryBuilder convertQuery(final QueryContext context, final Query query, final float boost) {
    if (query instanceof TermQuery) {
        return convertTermQuery(context, (TermQuery) query, boost);
    } else if (query instanceof TermRangeQuery) {
        return convertTermRangeQuery(context, (TermRangeQuery) query, boost);
    } else if (query instanceof PhraseQuery) {
        return convertPhraseQuery(context, (PhraseQuery) query, boost);
    } else if (query instanceof FuzzyQuery) {
        return convertFuzzyQuery(context, (FuzzyQuery) query, boost);
    } else if (query instanceof PrefixQuery) {
        return convertPrefixQuery(context, (PrefixQuery) query, boost);
    } else if (query instanceof WildcardQuery) {
        return convertWildcardQuery(context, (WildcardQuery) query, boost);
    } else if (query instanceof BooleanQuery) {
        final BooleanQuery booleanQuery = (BooleanQuery) query;
        return convertBooleanQuery(context, booleanQuery, boost);
    } else if (query instanceof MatchAllDocsQuery) {
        return QueryBuilders.matchAllQuery();
    } else if (query instanceof BoostQuery) {
        final BoostQuery boostQuery = (BoostQuery) query;
        return convertQuery(context, boostQuery.getQuery(), boostQuery.getBoost());
    }
    throw new InvalidQueryException(messages -> messages.addErrorsInvalidQueryUnknown(UserMessages.GLOBAL_PROPERTY_KEY), "Unknown q: "
            + query.getClass() + " => " + query);
}
 
Example 13
Source File: T_IEsQueryDao.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void t_queryByEsQueryDo2()throws Exception {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    QueryBuilder qb = QueryBuilders.matchAllQuery();
    searchSourceBuilder.query(qb);
    ShapeBuilder shapeBuilder = ShapeBuilder.newPoint(new Coordinate(116.402257, 39.914548));
    QueryBuilder qb2 = QueryBuilders.geoShapeQuery("geometry", shapeBuilder, ShapeRelation.CONTAINS);

    QueryBuilder qb3 = QueryBuilders.boolQuery().must(qb).filter(qb2);
    searchSourceBuilder.query(qb3);
   iEsQueryDao.query(searchSourceBuilder,"twitter","user","user2");
    /*logger.info(JSON.toJSONString(es));
    Assert.assertNotEquals("1", es.getStatus());*/
}
 
Example 14
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void doMatchAll(ConditionOptionCall<MatchAllQueryBuilder> opLambda) {
    MatchAllQueryBuilder builder = QueryBuilders.matchAllQuery();
    regQ(builder);
    if (opLambda != null) {
        opLambda.callback(builder);
    }
}
 
Example 15
Source File: EsAbstractConditionQuery.java    From fess with Apache License 2.0 5 votes vote down vote up
protected void doMatchAll(ConditionOptionCall<MatchAllQueryBuilder> opLambda) {
    MatchAllQueryBuilder builder = QueryBuilders.matchAllQuery();
    regQ(builder);
    if (opLambda != null) {
        opLambda.callback(builder);
    }
}
 
Example 16
Source File: ChnlZhihuSearchService.java    From albert with MIT License 5 votes vote down vote up
protected QueryBuilder createQuery(ZhihuSearchParam param){
	BoolQueryBuilder builder = QueryBuilders.boolQuery();
	
	boolean title = addTitleQuery(param.getTitle(), builder);
	
	if(title){
		return builder;
	}
	
	return QueryBuilders.matchAllQuery();
}
 
Example 17
Source File: IndexAnomalyDetectorActionHandler.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private void createAnomalyDetector() {
    try {
        QueryBuilder query = QueryBuilders.matchAllQuery();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(query).size(0).timeout(requestTimeout);

        SearchRequest searchRequest = new SearchRequest(ANOMALY_DETECTORS_INDEX).source(searchSourceBuilder);

        client.search(searchRequest, ActionListener.wrap(response -> onSearchAdResponse(response), exception -> onFailure(exception)));
    } catch (Exception e) {
        onFailure(e);
    }
}
 
Example 18
Source File: SearchBuilder.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 生成queryStringQuery查询
 * @param queryStr 查询关键字
 */
public SearchBuilder setStringQuery(String queryStr) {
    QueryBuilder queryBuilder;
    if (StrUtil.isNotEmpty(queryStr)) {
        queryBuilder = QueryBuilders.queryStringQuery(queryStr);
    } else {
        queryBuilder = QueryBuilders.matchAllQuery();
    }
    searchBuilder.query(queryBuilder);
    return this;
}
 
Example 19
Source File: ElasticsearchTransactionRepository.java    From servicecomb-pack with Apache License 2.0 4 votes vote down vote up
@Override
public PagingGlobalTransactions getGlobalTransactions(String state, int page, int size) {
  //ElasticsearchTemplate.prepareScroll() does not add sorting https://jira.spring.io/browse/DATAES-457
  long start = System.currentTimeMillis();
  PagingGlobalTransactions pagingGlobalTransactions;
  List<GlobalTransaction> globalTransactions = new ArrayList();
  try{
    IndicesExistsRequest request = new IndicesExistsRequest(INDEX_NAME);
    if (this.template.getClient().admin().indices().exists(request).actionGet().isExists()) {
      QueryBuilder query;
      if (state != null && state.trim().length() > 0) {
        query = QueryBuilders.termQuery("state.keyword", state);
      } else {
        query = QueryBuilders.matchAllQuery();
      }
      SearchResponse response = this.template.getClient().prepareSearch(INDEX_NAME)
          .setTypes(INDEX_TYPE)
          .setQuery(query)
          .addSort(SortBuilders.fieldSort("beginTime").order(SortOrder.DESC).unmappedType("date"))
          .setSize(size)
          .setFrom(page * size)
          .execute()
          .actionGet();
      ObjectMapper jsonMapper = new ObjectMapper();
      response.getHits().forEach(hit -> {
        try {
          GlobalTransactionDocument dto = jsonMapper
              .readValue(hit.getSourceAsString(), GlobalTransactionDocument.class);
          globalTransactions.add(dto);
        } catch (Exception e) {
          LOG.error(e.getMessage(), e);
        }
      });
      pagingGlobalTransactions = PagingGlobalTransactions.builder().page(page).size(size).total(response.getHits().getTotalHits())
          .globalTransactions(globalTransactions).elapsed(System.currentTimeMillis() - start).build();
    } else {
      LOG.warn("[alpha_global_transaction] index not exist");
      pagingGlobalTransactions = PagingGlobalTransactions.builder().page(page).size(size).total(0)
          .globalTransactions(globalTransactions).elapsed(System.currentTimeMillis() - start).build();
    }
  }catch (Exception ex){
    LOG.error(ex.getMessage(),ex);
    pagingGlobalTransactions = PagingGlobalTransactions.builder().page(page).size(size).total(0)
        .globalTransactions(globalTransactions).elapsed(System.currentTimeMillis() - start).build();
  }
  LOG.info("Query total hits {}, return page {}, size {}", pagingGlobalTransactions.getTotal(), page, size);
  return pagingGlobalTransactions;
}
 
Example 20
Source File: AST_Search.java    From elasticsearch-rest-command with The Unlicense 2 votes vote down vote up
public QueryBuilder getQueryBuilder() throws CommandException{
	//QueryBuilders.constantScoreQuery(queryBuilder)
	
	return (getInternalQuery() == null)? QueryBuilders.matchAllQuery():  getInternalQuery() ;

}