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

The following examples show how to use org.elasticsearch.index.query.BoolQueryBuilder#filter() . 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: AnomalyDetectorProfileRunner.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * Create search request to check if we have at least 1 anomaly score larger than 0 after AD job enabled time
 * @param detectorId detector id
 * @param enabledTime the time when AD job is enabled in milliseconds
 * @return the search request
 */
private SearchRequest createInittedEverRequest(String detectorId, long enabledTime) {
    BoolQueryBuilder filterQuery = new BoolQueryBuilder();
    filterQuery.filter(QueryBuilders.termQuery(AnomalyResult.DETECTOR_ID_FIELD, detectorId));
    filterQuery.filter(QueryBuilders.rangeQuery(AnomalyResult.EXECUTION_END_TIME_FIELD).gte(enabledTime));
    filterQuery.filter(QueryBuilders.rangeQuery(AnomalyResult.ANOMALY_SCORE_FIELD).gt(0));

    // I am only looking for last 1 occurrence and have no interest in the total number of documents that match the query.
    // ES will not try to count the number of documents and will be able to terminate the query as soon as 1 document
    // have been collected per segment.
    SearchSourceBuilder source = new SearchSourceBuilder().query(filterQuery).size(1).trackTotalHits(false);

    SearchRequest request = new SearchRequest(AnomalyResult.ANOMALY_RESULT_INDEX);
    request.source(source);
    return request;
}
 
Example 2
Source File: AnomalyDetectorProfileRunner.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * Create search request to get the latest anomaly result after AD job enabled time
 * @param detectorId detector id
 * @param enabledTime the time when AD job is enabled in milliseconds
 * @return the search request
 */
private SearchRequest createLatestAnomalyResultRequest(String detectorId, long enabledTime, long disabledTime, String[] index) {
    BoolQueryBuilder filterQuery = new BoolQueryBuilder();
    filterQuery.filter(QueryBuilders.termQuery(AnomalyResult.DETECTOR_ID_FIELD, detectorId));
    RangeQueryBuilder rangeBuilder = QueryBuilders.rangeQuery(AnomalyResult.EXECUTION_END_TIME_FIELD).gte(enabledTime);
    if (disabledTime >= enabledTime) {
        rangeBuilder.lte(disabledTime);
    }
    filterQuery.filter(rangeBuilder);

    FieldSortBuilder sortQuery = new FieldSortBuilder(AnomalyResult.EXECUTION_END_TIME_FIELD).order(SortOrder.DESC);

    // I am only looking for last 1 occurrence and have no interest in the total number of documents that match the query.
    // ES will not try to count the number of documents and will be able to terminate the query as soon as 1 document
    // have been collected per segment.
    SearchSourceBuilder source = new SearchSourceBuilder().query(filterQuery).size(1).sort(sortQuery).trackTotalHits(false);

    SearchRequest request = new SearchRequest(index);
    request.source(source);
    return request;
}
 
Example 3
Source File: ElasticsearchQueryBuilder.java    From presto with Apache License 2.0 6 votes vote down vote up
public static QueryBuilder buildSearchQuery(ConnectorSession session, TupleDomain<ElasticsearchColumnHandle> constraint, Optional<String> query)
{
    BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
    if (constraint.getDomains().isPresent()) {
        for (Map.Entry<ElasticsearchColumnHandle, Domain> entry : constraint.getDomains().get().entrySet()) {
            ElasticsearchColumnHandle column = entry.getKey();
            Domain domain = entry.getValue();

            checkArgument(!domain.isNone(), "Unexpected NONE domain for %s", column.getName());
            if (!domain.isAll()) {
                queryBuilder.filter(new BoolQueryBuilder().must(buildPredicate(session, column.getName(), domain, column.getType())));
            }
        }
    }
    query.map(QueryStringQueryBuilder::new)
            .ifPresent(queryBuilder::must);

    if (queryBuilder.hasClauses()) {
        return queryBuilder;
    }
    return new MatchAllQueryBuilder();
}
 
Example 4
Source File: ElasticSearchCleanupComponentBrowseTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
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 5
Source File: PointsResource.java    From 21-points with Apache License 2.0 5 votes vote down vote up
/**
 * SEARCH  /_search/points?query=:query : search for the points corresponding
 * to the query.
 *
 * @param query the query of the points search
 * @param pageable the pagination information
 * @return the result of the search
 */
@GetMapping("/_search/points")
@Timed
public ResponseEntity<List<Points>> searchPoints(@RequestParam String query, Pageable pageable) {
    log.debug("REST request to search for a page of Points for query {}", query);
    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
    if (SecurityUtils.isAuthenticated() && !SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)) {
        queryBuilder = queryBuilder.filter(matchQuery("user.login",
            SecurityUtils.getCurrentUserLogin().orElse("")));
    }
    Page<Points> page = pointsSearchRepository.search(queryBuilder, pageable);
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/points");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 6
Source File: SiteAwareElasticsearchService.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void updateFilters(final SearchRequest request) {
    super.updateFilters(request);

    BoolQueryBuilder mainQuery = (BoolQueryBuilder) request.source().query();

    Authentication auth = null;
    SecurityContext context = SecurityContextHolder.getContext();
    if (context != null) {
        auth = context.getAuthentication();
    }

    // Include all public items
    BoolQueryBuilder securityQuery = boolQuery()
            .should(boolQuery().mustNot(existsQuery(roleFieldName)))
            .should(matchQuery(roleFieldName, "anonymous"));

    if (auth != null && !(auth instanceof AnonymousAuthenticationToken) && isNotEmpty(auth.getAuthorities())) {
        logger.debug("Filtering search results for roles: {}", auth.getAuthorities());
        securityQuery.should(matchQuery(roleFieldName, auth.getAuthorities().stream()
                        .map(Object::toString)
                        .collect(joining(" "))));
    } else {
        logger.debug("Filtering search to show only public items");
    }

    mainQuery.filter(boolQuery().must(securityQuery));
}
 
Example 7
Source File: Select.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * 过滤查询
 * 示例:筛选品牌为小米的记录
 */
@Test
public void test3() throws IOException {
    //2.封装查询请求
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    // 布尔查询构建器
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    // 词条查询构建器
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "小米");

    boolQueryBuilder.filter(termQueryBuilder);

    searchSourceBuilder.query(boolQueryBuilder);
    searchRequest.source(searchSourceBuilder);
}
 
Example 8
Source File: ContentTypeBasedDataFetcher.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected void addFieldFilterFromObjectField(String path, ObjectField filter, BoolQueryBuilder query,
                                             DataFetchingEnvironment env) {
    if (filter.getValue() instanceof ArrayValue) {
        ArrayValue actualFilters = (ArrayValue) filter.getValue();
        switch (filter.getName()) {
            case ARG_NAME_NOT:
                BoolQueryBuilder notQuery = boolQuery();
                actualFilters.getValues()
                    .forEach(notFilter -> ((ObjectValue) notFilter).getObjectFields()
                        .forEach(notField -> addFieldFilterFromObjectField(path, notField, notQuery, env)));
                notQuery.filter().forEach(query::mustNot);
                break;
            case ARG_NAME_AND:
                actualFilters.getValues()
                    .forEach(andFilter -> ((ObjectValue) andFilter).getObjectFields()
                        .forEach(andField -> addFieldFilterFromObjectField(path, andField, query, env)));
                break;
            case ARG_NAME_OR:
                BoolQueryBuilder tempQuery = boolQuery();
                BoolQueryBuilder orQuery = boolQuery();
                actualFilters.getValues().forEach(orFilter ->
                    ((ObjectValue) orFilter).getObjectFields()
                        .forEach(orField -> addFieldFilterFromObjectField(path, orField, tempQuery, env)));
                tempQuery.filter().forEach(orQuery::should);
                query.filter(boolQuery().must(orQuery));
                break;
            default:
                // never happens
        }
    } else if (!(filter.getValue() instanceof VariableReference) ||
                env.getVariables().containsKey(((VariableReference)filter.getValue()).getName())) {
        query.filter(getFilterQueryFromObjectField(path, filter, env));
    }
}
 
Example 9
Source File: DetectorMappingRepositoryImpl.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
@Override
public MatchingDetectorsResponse findMatchingDetectorMappings(List<Map<String, String>> tagsList) {
    try {
        List<BytesReference> refList = new ArrayList<>();
        for (Map<String, String> tags : tagsList) {
            XContentBuilder xContent = XContentFactory.jsonBuilder();
            xContent.map(tags);
            refList.add(BytesReference.bytes(xContent));
        }
        PercolateQueryBuilder percolateQuery = new PercolateQueryBuilder(PercolatorDetectorMapping.QUERY_KEYWORD,
                refList, XContentType.JSON);
        val termQuery = QueryBuilders.termQuery("aa_enabled", true);

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.filter(percolateQuery);
        boolQueryBuilder.filter(termQuery);

        SearchSourceBuilder searchSourceBuilder = elasticsearchUtil.getSourceBuilder(boolQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(elasticSearchProperties.getConfig().getConnectionTimeout()));
        //FIXME setting default result set size to 500.
        // This is for returning detectors matching for set of metrics
        searchSourceBuilder.size(500);
        return getDetectorMappings(searchSourceBuilder, tagsList);
    } catch (IOException e) {
        log.error("Error ES lookup", e);
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: ContentTypeBasedDataFetcher.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected void addFieldFilterFromMapEntry(String path, Map.Entry<String, Object> filter, BoolQueryBuilder query,
                                          DataFetchingEnvironment env) {
    if (filter.getValue() instanceof List) {
        List<Map<String, Object>> actualFilters = (List<Map<String, Object>>) filter.getValue();
        switch (filter.getKey()) {
            case ARG_NAME_NOT:
                BoolQueryBuilder notQuery = boolQuery();
                actualFilters.forEach(notFilter -> notFilter.entrySet()
                        .forEach(notField -> addFieldFilterFromMapEntry(path, notField, notQuery, env)));
                notQuery.filter().forEach(query::mustNot);
                break;
            case ARG_NAME_AND:
                actualFilters.forEach(andFilter -> andFilter.entrySet()
                        .forEach(andField -> addFieldFilterFromMapEntry(path, andField, query, env)));
                break;
            case ARG_NAME_OR:
                BoolQueryBuilder tempQuery = boolQuery();
                BoolQueryBuilder orQuery = boolQuery();
                actualFilters.forEach(orFilter -> orFilter.entrySet()
                        .forEach(orField -> addFieldFilterFromMapEntry(path, orField, tempQuery, env)));
                tempQuery.filter().forEach(orQuery::should);
                query.filter(boolQuery().must(orQuery));
                break;
            default:
                // never happens
        }
    } else {
        query.filter(getFilterQueryFromMapEntry(path, filter));
    }
}
 
Example 11
Source File: BloodPressureResource.java    From 21-points with Apache License 2.0 5 votes vote down vote up
/**
 * SEARCH  /_search/blood-pressures?query=:query : search for the bloodPressure corresponding
 * to the query.
 *
 * @param query the query of the bloodPressure search
 * @param pageable the pagination information
 * @return the result of the search
 */
@GetMapping("/_search/blood-pressures")
@Timed
public ResponseEntity<List<BloodPressure>> searchBloodPressures(@RequestParam String query, Pageable pageable) {
    log.debug("REST request to search for a page of BloodPressures for query {}", query);
    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(queryStringQuery(query));
    if (SecurityUtils.isAuthenticated() && !SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)) {
        queryBuilder = queryBuilder.filter(matchQuery("user.login",
            SecurityUtils.getCurrentUserLogin().orElse("")));
    }
    Page<BloodPressure> page = bloodPressureSearchRepository.search(queryBuilder, pageable);
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/blood-pressures");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 12
Source File: ESQueryMapper.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private QueryBuilder getFilter(ExtraQuery extraQuery) {
  BoolQueryBuilder bool = new BoolQueryBuilder();
  for (Entry<String, Object> e : extraQuery.getQueryBy().entrySet()) {
    Object value = e.getValue();
    String key = e.getKey();
    Optional<Object> queryResult = getPlaceholderQueryResult(extraQuery, value);
    if (queryResult.isPresent()) {
      extraQuery.filter(key, queryResult.get());
      bool.filter(QueryBuilders.termQuery(key, queryResult.get()));
    } else {
      bool.filter(QueryBuilders.termQuery(key, value));
    }
  }
  return bool;
}
 
Example 13
Source File: FactSearchManager.java    From act-platform with ISC License 4 votes vote down vote up
private QueryBuilder buildFactExistenceQuery(FactExistenceSearchCriteria criteria) {
  // Define all filters on direct Fact fields. Every field from the criteria must match.
  BoolQueryBuilder rootQuery = boolQuery()
          .filter(termQuery("typeID", toString(criteria.getFactTypeID())))
          .filter(termQuery("sourceID", toString(criteria.getOriginID())))
          .filter(termQuery("organizationID", toString(criteria.getOrganizationID())))
          .filter(termQuery("accessMode", toString(criteria.getAccessMode())))
          // Consider 'confidence' to be equal inside a given interval.
          .filter(rangeQuery("confidence")
                  .gt(criteria.getConfidence() - CONFIDENCE_EQUALITY_INTERVAL / 2)
                  .lt(criteria.getConfidence() + CONFIDENCE_EQUALITY_INTERVAL / 2));

  if (criteria.getFactValue() != null) {
    // Fact values must match exactly if given.
    rootQuery.filter(termQuery("value", criteria.getFactValue()));
  } else {
    // If 'value' isn't given make sure that it's also not set on any existing Fact.
    rootQuery.mustNot(existsQuery("value"));
  }

  // This clause is required when searching for existing meta Facts.
  if (criteria.getInReferenceTo() != null) {
    rootQuery.filter(termQuery("inReferenceTo", toString(criteria.getInReferenceTo())));
  }

  // These clauses are required when searching for regular Facts.
  if (!CollectionUtils.isEmpty(criteria.getObjects())) {
    // The number of bound Objects must match (stored as a de-normalized field).
    rootQuery.filter(termQuery("objectCount", criteria.getObjects().size()));

    // Define filters on nested Objects. Also all Objects must match.
    for (FactExistenceSearchCriteria.ObjectExistence object : criteria.getObjects()) {
      BoolQueryBuilder objectsQuery = boolQuery()
              .filter(termQuery("objects.id", toString(object.getObjectID())))
              .filter(termQuery("objects.direction", toString(object.getDirection())));
      rootQuery.filter(nestedQuery("objects", objectsQuery, ScoreMode.None));
    }
  }

  return rootQuery;
}
 
Example 14
Source File: RundeckMavenResource.java    From nexus3-rundeck-plugin with MIT License 4 votes vote down vote up
@GET
@Path("version")
@Produces(APPLICATION_JSON)
public List<RundeckXO> version(
        @DefaultValue("10") @QueryParam("l") int limit,
        @QueryParam("r") String repository,
        @QueryParam("g") String groupId,
        @QueryParam("a") String artifactId,
        @QueryParam("c") String classifier,
        @QueryParam("p") String extension
) {

    log.debug("param value, repository: {}, limit: {}, groupId: {}, artifactId: {}, classifier: {}, extension: {}", repository, limit, groupId, artifactId, classifier, extension);

    BoolQueryBuilder query = boolQuery();
    query.filter(termQuery("format", "maven2"));

    if (!isBlank(repository)) {
        query.filter(termQuery("repository_name", repository));
    }
    if (!isBlank(groupId)) {
        query.filter(termQuery("attributes.maven2.groupId", groupId));
    }
    if (!isBlank(artifactId)) {
        query.filter(termQuery("attributes.maven2.artifactId", artifactId));
    }
    if (!isBlank(classifier)) {
        query.filter(termQuery("assets.attributes.maven2.classifier", classifier));
    }
    if (!isBlank(extension)) {
        query.filter(termQuery("assets.attributes.maven2.extension", extension));
    }

    log.debug("rundeck maven version query: {}", query);
    SearchResponse result = searchService.searchUnrestricted(
            query,
            Collections.singletonList(new FieldSortBuilder("assets.attributes.content.last_modified").order(SortOrder.DESC)),
            0,
            limit
    );
    return Arrays.stream(result.getHits().hits())
            .map(this::his2RundeckXO)
            .collect(Collectors.toList());
}
 
Example 15
Source File: DockerContentDigestSearchContribution.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.filter(QueryBuilders.termQuery(type, value));
  }
}
 
Example 16
Source File: ContentTypeBasedDataFetcher.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object doGet(final DataFetchingEnvironment env) {
    Field field = env.getMergedField().getSingleField();
    String fieldName = field.getName();

    // Get arguments for pagination & sorting
    int offset = Optional.ofNullable(env.<Integer>getArgument(ARG_NAME_OFFSET)).orElse(0);
    int limit = Optional.ofNullable(env.<Integer>getArgument(ARG_NAME_LIMIT)).orElse(defaultLimit);
    String sortBy = Optional.ofNullable(env.<String>getArgument(ARG_NAME_SORT_BY)).orElse(defaultSortField);
    String sortOrder = Optional.ofNullable(env.<String>getArgument(ARG_NAME_SORT_ORDER)).orElse(defaultSortOrder);

    List<String> queryFieldIncludes = new LinkedList<>();
    // Add content-type to includes, we might need it for a GraphQL TypeResolver
    queryFieldIncludes.add(QUERY_FIELD_NAME_CONTENT_TYPE);

    List<Map<String, Object>> items = new LinkedList<>();
    Map<String, Object> result = new HashMap<>(2);
    result.put(FIELD_NAME_ITEMS, items);

    // Setup the ES query
    SearchSourceBuilder source = new SearchSourceBuilder();
    BoolQueryBuilder query = boolQuery();
    source
        .query(query)
        .from(offset)
        .size(limit)
        .sort(sortBy, SortOrder.fromString(sortOrder));

    StopWatch watch = new StopWatch(field.getName() + " - " + field.getAlias());

    watch.start("build filters");

    // Filter by the content-type
    switch (fieldName) {
        case FIELD_NAME_CONTENT_ITEMS:
            query.filter(existsQuery(QUERY_FIELD_NAME_CONTENT_TYPE));
            break;
        case FIELD_NAME_PAGES:
            query.filter(regexpQuery(QUERY_FIELD_NAME_CONTENT_TYPE, CONTENT_TYPE_REGEX_PAGE));
            break;
        case FIELD_NAME_COMPONENTS:
            query.filter(regexpQuery(QUERY_FIELD_NAME_CONTENT_TYPE, CONTENT_TYPE_REGEX_COMPONENT));
            break;
        default:
            // Get the content-type name from the field name
            query.filter(termQuery(QUERY_FIELD_NAME_CONTENT_TYPE, getOriginalName(fieldName)));
            break;
    }

    // Check the selected fields to build the ES query
    Optional<Field> itemsField = field.getSelectionSet().getSelections()
                        .stream()
                        .map(f -> (Field) f)
                        .filter(f -> f.getName().equals(FIELD_NAME_ITEMS))
                        .findFirst();
    if (itemsField.isPresent()) {
        List<Selection> selections = itemsField.get().getSelectionSet().getSelections();
        selections.forEach(selection -> processSelection(StringUtils.EMPTY, selection, query, queryFieldIncludes,
         env));
    }

    // Only fetch the selected fields for better performance
    source.fetchSource(queryFieldIncludes.toArray(new String[0]), new String[0]);
    watch.stop();

    logger.debug("Executing query: {}", source);

    watch.start("searching items");
    SearchResponse response = elasticsearch.search(new SearchRequest().source(source));
    watch.stop();

    watch.start("processing items");
    result.put(FIELD_NAME_TOTAL, response.getHits().totalHits);
    if (response.getHits().totalHits > 0) {
        for(SearchHit hit :  response.getHits().getHits()) {
            items.add(fixItems(hit.getSourceAsMap()));
        }
    }
    watch.stop();

    if (logger.isTraceEnabled()) {
        logger.trace(watch.prettyPrint());
    }

    return result;
}
 
Example 17
Source File: FactSearchManager.java    From act-platform with ISC License 4 votes vote down vote up
private void applySimpleFilterQueries(FactSearchCriteria criteria, BoolQueryBuilder rootQuery) {
  if (!CollectionUtils.isEmpty(criteria.getFactID())) {
    rootQuery.filter(termsQuery("_id", toString(criteria.getFactID())));
  }

  if (!CollectionUtils.isEmpty(criteria.getFactTypeID())) {
    rootQuery.filter(termsQuery("typeID", toString(criteria.getFactTypeID())));
  }

  if (!CollectionUtils.isEmpty(criteria.getFactValue())) {
    rootQuery.filter(termsQuery("value", criteria.getFactValue()));
  }

  if (!CollectionUtils.isEmpty(criteria.getInReferenceTo())) {
    rootQuery.filter(termsQuery("inReferenceTo", toString(criteria.getInReferenceTo())));
  }

  if (!CollectionUtils.isEmpty(criteria.getOrganizationID())) {
    rootQuery.filter(termsQuery("organizationID", toString(criteria.getOrganizationID())));
  }

  if (!CollectionUtils.isEmpty(criteria.getOriginID())) {
    rootQuery.filter(termsQuery("sourceID", toString(criteria.getOriginID())));
  }

  if (!CollectionUtils.isEmpty(criteria.getObjectID())) {
    rootQuery.filter(nestedQuery("objects", termsQuery("objects.id", toString(criteria.getObjectID())), ScoreMode.None));
  }

  if (!CollectionUtils.isEmpty(criteria.getObjectTypeID())) {
    rootQuery.filter(nestedQuery("objects", termsQuery("objects.typeID", toString(criteria.getObjectTypeID())), ScoreMode.None));
  }

  if (!CollectionUtils.isEmpty(criteria.getObjectValue())) {
    rootQuery.filter(nestedQuery("objects", termsQuery("objects.value", criteria.getObjectValue()), ScoreMode.None));
  }

  if (criteria.getFactBinding() != null) {
    rootQuery.filter(termQuery("objectCount", criteria.getFactBinding().getObjectCount()));
  }
}
 
Example 18
Source File: PyPiSearchUtils.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * XML-RPC request parser capable of ad-hoc parsing of search requests generated by pip. Only search requests are
 * expected (based on analyzing pip traffic) and exceptions are raised if the assumption is unmet.
 */
public static QueryBuilder parseSearchRequest(final String repository, final InputStream in) throws Exception {
  checkNotNull(repository);
  checkNotNull(in);

  DocumentBuilderFactory factory = SafeXml.newdocumentBuilderFactory();
  factory.setValidating(false);

  DocumentBuilder builder = factory.newDocumentBuilder();
  XPathFactory xPathFactory = XPathFactory.newInstance();
  XPath xPath = xPathFactory.newXPath();
  Document document = builder.parse(in);

  // There are other XML-RPC operations that are supported by the PyPI XML-RPC API. However, at this time we only
  // support (a subset of) search operations specific to pip, so if something else comes in, we need to throw here.
  String methodName = (String) xPath.evaluate(METHOD_NAME_EXPRESSION, document, XPathConstants.STRING);
  if (!"search".equals(methodName)) {
    throw new UnsupportedOperationException("Only search methods supported, found: " + methodName);
  }

  // While we can also handle AND operations using ES, at this time we are only supporting the minimum feature set
  // necessary to support "pip search" requests. Since pip search only uses OR operations, that is all we support.
  String searchOperator = (String) xPath.evaluate(SEARCH_OPERATOR_EXPRESSION, document, XPathConstants.STRING);
  if (!"or".equals(searchOperator)) {
    throw new UnsupportedOperationException("Only or-search operations supported, found: " + searchOperator);
  }

  BoolQueryBuilder query = QueryBuilders.boolQuery();

  NodeList members = (NodeList) xPath.evaluate(MEMBER_LIST_EXPRESSION, document, XPathConstants.NODESET);
  for (int index = 0, count = members.getLength(); index < count; index++) {
    Node item = members.item(index);
    String name = (String) xPath.evaluate(PARAMETER_NAME_EXPRESSION, item, XPathConstants.STRING);
    if (!VALID_SEARCH_KEYS.contains(name)) {
      throw new UnsupportedOperationException("Search key not supported, found: " + name);
    }
    addSubqueries(xPath, query, name, item);
  }

  query.minimumNumberShouldMatch(1);
  query.filter(QueryBuilders.termQuery(REPOSITORY_NAME, repository));

  return query;
}
 
Example 19
Source File: Application.java    From ElasticSearch with MIT License 4 votes vote down vote up
@PostMapping("query/book/novel")
@ResponseBody
public ResponseEntity query(
        @RequestParam(name = "author", required = false) String author,
        @RequestParam(name = "title", required = false) String title,
        @RequestParam(name = "gt_word_count", defaultValue = "0") int gtWordCount,
        @RequestParam(name = "lt_word_count", required = false) Integer ltWordCount) {

    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

    if (author != null) {
        boolQuery.must(QueryBuilders.matchQuery("author", author));
    }

    if (title != null) {
        boolQuery.must(QueryBuilders.matchQuery("title", title));
    }

    RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
    if (ltWordCount != null && ltWordCount > 0) {
        rangeQuery.to(ltWordCount);
    }
    boolQuery.filter(rangeQuery);

    SearchRequestBuilder builder = client.prepareSearch(BOOK_INDEX).setTypes(BOOK_TYPE_NOVEL)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(boolQuery)
            .setFrom(0)
            .setSize(10);

    logger.debug(builder.toString());

    SearchResponse response = builder.get();

    List result = new ArrayList<Map<String, Object>>();
    for (SearchHit hit : response.getHits()) {
        result.add(hit.getSourceAsMap());
    }

    return new ResponseEntity(result, HttpStatus.OK);

}
 
Example 20
Source File: ElasticsearchQueryBuilder.java    From presto with Apache License 2.0 4 votes vote down vote up
private static QueryBuilder buildTermQuery(BoolQueryBuilder queryBuilder, ConnectorSession session, String columnName, Domain domain, Type type)
{
    for (Range range : domain.getValues().getRanges().getOrderedRanges()) {
        BoolQueryBuilder rangeQueryBuilder = new BoolQueryBuilder();
        Set<Object> valuesToInclude = new HashSet<>();
        checkState(!range.isAll(), "Invalid range for column: " + columnName);
        if (range.isSingleValue()) {
            valuesToInclude.add(range.getLow().getValue());
        }
        else {
            if (!range.getLow().isLowerUnbounded()) {
                switch (range.getLow().getBound()) {
                    case ABOVE:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).gt(getValue(session, type, range.getLow().getValue())));
                        break;
                    case EXACTLY:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).gte(getValue(session, type, range.getLow().getValue())));
                        break;
                    case BELOW:
                        throw new IllegalArgumentException("Low marker should never use BELOW bound");
                    default:
                        throw new AssertionError("Unhandled bound: " + range.getLow().getBound());
                }
            }
            if (!range.getHigh().isUpperUnbounded()) {
                switch (range.getHigh().getBound()) {
                    case EXACTLY:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).lte(getValue(session, type, range.getHigh().getValue())));
                        break;
                    case BELOW:
                        rangeQueryBuilder.filter(new RangeQueryBuilder(columnName).lt(getValue(session, type, range.getHigh().getValue())));
                        break;
                    case ABOVE:
                        throw new IllegalArgumentException("High marker should never use ABOVE bound");
                    default:
                        throw new AssertionError("Unhandled bound: " + range.getHigh().getBound());
                }
            }
        }

        if (valuesToInclude.size() == 1) {
            rangeQueryBuilder.filter(new TermQueryBuilder(columnName, getValue(session, type, getOnlyElement(valuesToInclude))));
        }
        queryBuilder.should(rangeQueryBuilder);
    }
    return queryBuilder;
}