Java Code Examples for org.apache.lucene.search.join.ScoreMode

The following examples show how to use org.apache.lucene.search.join.ScoreMode. 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
@Test
void mapQueryRuleAttributeSearchReferencedAttribute() {
  QueryRule queryRule = mock(QueryRule.class);
  when(queryRule.getField()).thenReturn("attr");
  when(queryRule.getValue()).thenReturn("val");

  Attribute refIdAttribute = mock(Attribute.class);
  when(refIdAttribute.getDataType()).thenReturn(STRING);
  EntityType refEntityType = mock(EntityType.class);
  when(refEntityType.getIdAttribute()).thenReturn(refIdAttribute);
  when(documentIdGenerator.generateId(refIdAttribute)).thenReturn("refAttr");
  Attribute attribute = mock(Attribute.class);
  when(attribute.hasRefEntity()).thenReturn(true);
  when(attribute.getRefEntity()).thenReturn(refEntityType);
  when(documentIdGenerator.generateId(attribute)).thenReturn("attr");

  EntityType entityType = mock(EntityType.class);
  when(entityType.getIndexingDepth()).thenReturn(1);
  when(entityType.getAttributeByName("attr")).thenReturn(attribute);

  QueryBuilder queryBuilder = queryClauseSearchGenerator.mapQueryRule(queryRule, entityType);
  QueryBuilder expectedQueryBuilder =
      QueryBuilders.nestedQuery(
          "attr", QueryBuilders.matchQuery("attr.refAttr", "val"), ScoreMode.Avg);
  assertQueryBuilderEquals(expectedQueryBuilder, queryBuilder);
}
 
Example 2
@Test
void mapQueryRuleAttributeSearchReferencedAttribute() {
  when(queryRule.getField()).thenReturn("attr");
  when(queryRule.getValue()).thenReturn("val");

  when(entityType.getIndexingDepth()).thenReturn(1);
  when(entityType.getAttributeByName("attr")).thenReturn(attribute);
  when(attribute.hasRefEntity()).thenReturn(true);
  when(attribute.getRefEntity()).thenReturn(refEntityType);
  when(refIdAttribute.getDataType()).thenReturn(STRING);
  when(refEntityType.getIdAttribute()).thenReturn(refIdAttribute);
  when(documentIdGenerator.generateId(refIdAttribute)).thenReturn("refAttr");
  when(documentIdGenerator.generateId(attribute)).thenReturn("attr");

  QueryBuilder queryBuilder = searchQueryGenerator.mapQueryRule(queryRule, entityType);
  QueryBuilder expectedQueryBuilder =
      QueryBuilders.nestedQuery(
          "attr",
          simpleQueryStringQuery("val").field("attr.refAttr").defaultOperator(AND),
          ScoreMode.Avg);
  assertQueryBuilderEquals(expectedQueryBuilder, queryBuilder);
}
 
Example 3
@Test
public void shouldReturnBooksForGivenBucket() {
    Book book1 = new Book(RandomUtil.randomString(5, 10), "test1", System.currentTimeMillis());
    Book book2 = new Book(RandomUtil.randomString(5, 10), "test2", System.currentTimeMillis());

    Map<Integer, Collection<String>> map1 = new HashMap<>();
    map1.put(1, Arrays.asList("test1", "test2"));

    Map<Integer, Collection<String>> map2 = new HashMap<>();
    map2.put(1, Arrays.asList("test3", "test4"));

    book1.setBuckets(map1);
    book2.setBuckets(map2);

    repository.saveAll(Arrays.asList(book1, book2));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.Total))
        .build();

    Page<Book> books = repository.search(searchQuery);
    Assertions.assertThat(books.getContent()).hasSize(1);
}
 
Example 4
@Test
public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() {
    //given
    List<IndexQuery> indexQueries = createPerson();

    //when
    elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
    elasticsearchTemplate.bulkIndex(indexQueries);
    elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);

    //then
    BoolQueryBuilder builder = boolQuery();
    builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.Total))
        .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()),
            ScoreMode.Total));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(builder)
        .build();

    Page<PersonMultipleLevelNested> personIndexed =
        elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class);
    assertThat(personIndexed, is(notNullValue()));
    assertThat(personIndexed.getTotalElements(), is(1L));
    assertThat(personIndexed.getContent().get(0).getId(), is("1"));
}
 
Example 5
@Test
public void shouldReturnBooksForGivenBucket() {
    Book book1 = new Book(RandomUtil.randomString(5, 10), "test1", System.currentTimeMillis());
    Book book2 = new Book(RandomUtil.randomString(5, 10), "test2", System.currentTimeMillis());

    Map<Integer, Collection<String>> map1 = new HashMap<>();
    map1.put(1, Arrays.asList("test1", "test2"));

    Map<Integer, Collection<String>> map2 = new HashMap<>();
    map2.put(1, Arrays.asList("test3", "test4"));

    book1.setBuckets(map1);
    book2.setBuckets(map2);

    repository.saveAll(Arrays.asList(book1, book2));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.Total))
        .build();

    Page<Book> books = repository.search(searchQuery);
    Assertions.assertThat(books.getContent()).hasSize(1);
}
 
Example 6
@Test
public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() {
    //given
    List<IndexQuery> indexQueries = createPerson();

    //when
    elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
    elasticsearchTemplate.bulkIndex(indexQueries);
    elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);

    //then
    BoolQueryBuilder builder = boolQuery();
    builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.Total))
        .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()),
            ScoreMode.Total));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(builder)
        .build();

    Page<PersonMultipleLevelNested> personIndexed =
        elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class);
    assertThat(personIndexed, is(notNullValue()));
    assertThat(personIndexed.getTotalElements(), is(1L));
    assertThat(personIndexed.getContent().get(0).getId(), is("1"));
}
 
Example 7
private QueryBuilder getFilter(SyncData data) {
  BoolQueryBuilder builder = boolQuery();
  HashMap<String, Object> syncBy = data.getSyncBy();
  if (syncBy.isEmpty()) {
    throw new InvalidConfigException("No data used to do sync(update/delete) filter");
  }
  for (Entry<String, Object> entry : syncBy.entrySet()) {
    String[] key = entry.getKey().split("\\.");
    if (key.length == 2) {
      builder.filter(nestedQuery(key[0], boolQuery().filter(getSingleFilter(entry)), ScoreMode.Avg));
    } else if (key.length == 1) {
      builder.filter(getSingleFilter(entry));
    } else {
      logger.error("Only support one level nested obj for the time being");
    }
  }
  return builder;
}
 
Example 8
@Test
void generateOneQueryRuleNotEqualsCompoundPartString() {
  String value = "value";
  Query<Entity> q = new QueryImpl<>().not().eq(PREFIX + refCompoundPart0AttributeName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      boolQuery()
          .mustNot(
              constantScoreQuery(
                  nestedQuery(
                      REF_ENTITY_ATT,
                      termQuery(
                          PREFIX + refCompoundPart0AttributeName + '.' + FIELD_NOT_ANALYZED,
                          value),
                      ScoreMode.Avg)));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 9
Source Project: elasticsearch-learning-to-rank   Source File: LoggingIT.java    License: Apache License 2.0 6 votes vote down vote up
public void prepareModels() throws Exception {
    List<StoredFeature> features = new ArrayList<>(3);
    features.add(new StoredFeature("text_feature1", Collections.singletonList("query"), "mustache",
            QueryBuilders.matchQuery("field1", "{{query}}").toString()));
    features.add(new StoredFeature("text_feature2", Collections.singletonList("query"), "mustache",
            QueryBuilders.matchQuery("field2", "{{query}}").toString()));
    features.add(new StoredFeature("numeric_feature1", Collections.singletonList("query"), "mustache",
            new FunctionScoreQueryBuilder(QueryBuilders.matchAllQuery(), new FieldValueFactorFunctionBuilder("scorefield1")
                    .factor(FACTOR)
                    .modifier(FieldValueFactorFunction.Modifier.LN2P)
                    .missing(0F)).scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY).toString()));
    features.add(new StoredFeature("derived_feature", Collections.singletonList("query"), "derived_expression",
            "100"));

    StoredFeatureSet set = new StoredFeatureSet("my_set", features);
    addElement(set);
    StoredLtrModel model = new StoredLtrModel("my_model", set,
            new StoredLtrModel.LtrModelDefinition("model/linear",
                    LinearRankerParserTests.generateRandomModelString(set), true));
    addElement(model);
}
 
Example 10
Source Project: elasticsearch-learning-to-rank   Source File: LoggingIT.java    License: Apache License 2.0 6 votes vote down vote up
public void prepareModelsExtraLogging() throws Exception {
    List<StoredFeature> features = new ArrayList<>(3);
    features.add(new StoredFeature("text_feature1", Collections.singletonList("query"), "mustache",
            QueryBuilders.matchQuery("field1", "{{query}}").toString()));
    features.add(new StoredFeature("text_feature2", Collections.singletonList("query"), "mustache",
            QueryBuilders.matchQuery("field2", "{{query}}").toString()));
    features.add(new StoredFeature("numeric_feature1", Collections.singletonList("query"), "mustache",
            new FunctionScoreQueryBuilder(QueryBuilders.matchAllQuery(), new FieldValueFactorFunctionBuilder("scorefield1")
                    .factor(FACTOR)
                    .modifier(FieldValueFactorFunction.Modifier.LN2P)
                    .missing(0F)).scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY).toString()));
    features.add(new StoredFeature("derived_feature", Collections.singletonList("query"), "derived_expression",
            "100"));
    features.add(new StoredFeature("extra_logging_feature", Arrays.asList("query"), ScriptFeature.TEMPLATE_LANGUAGE,
            "{\"lang\": \"native\", \"source\": \"feature_extractor_extra_logging\", \"params\": {}}"));

    StoredFeatureSet set = new StoredFeatureSet("my_set", features);
    addElement(set);
    StoredLtrModel model = new StoredLtrModel("my_model", set,
            new StoredLtrModel.LtrModelDefinition("model/linear",
                    LinearRankerParserTests.generateRandomModelString(set), true));
    addElement(model);
}
 
Example 11
@Override
public Searcher with(String query, int fuzziness, boolean phraseMatches) {
    String queryString = query;
    try {
        if (!hasLuceneOperators(query)) {
            if (phraseMatches) {
                queryString = "\"" + query + "\"" + (fuzziness == 0 ? "": "~" + fuzziness);
            } else if (fuzziness > 0) {
                queryString = Stream.of(query.split(" ")).map(s -> s + "~" + fuzziness).collect(Collectors.joining(" "));
            }
        } else if (fuzziness != 0 || phraseMatches) {
            LOGGER.info("detected lucene operators in \"{}\", fuzziness and phrase match won't be applied", query);
        }
    } catch (org.apache.lucene.queryparser.classic.ParseException e) {
        LOGGER.warn("cannot parse query. Sending query as string query", e);
    }
    this.boolQuery.must(new MatchAllQueryBuilder());
    this.boolQuery.must(new QueryStringQueryBuilder(queryString).defaultField("*"));
    this.boolQuery.should(new HasChildQueryBuilder("NamedEntity", new QueryStringQueryBuilder(queryString).defaultField("mentionNorm"), ScoreMode.None));
    return this;
}
 
Example 12
Source Project: metron   Source File: ElasticsearchMetaAlertSearchDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SearchResponse search(SearchRequest searchRequest) throws InvalidSearchException {
  // Wrap the query to also get any meta-alerts.
  QueryBuilder qb = constantScoreQuery(boolQuery()
      .must(boolQuery()
          .should(new QueryStringQueryBuilder(searchRequest.getQuery()))
          .should(nestedQuery(
              MetaAlertConstants.ALERT_FIELD,
              new QueryStringQueryBuilder(searchRequest.getQuery()),
              ScoreMode.None
              )
          )
      )
      // Ensures that it's a meta alert with active status or that it's an alert (signified by
      // having no status field)
      .must(boolQuery()
          .should(termQuery(MetaAlertConstants.STATUS_FIELD,
              MetaAlertStatus.ACTIVE.getStatusString()))
          .should(boolQuery().mustNot(existsQuery(MetaAlertConstants.STATUS_FIELD)))
      )
      .mustNot(existsQuery(MetaAlertConstants.METAALERT_FIELD))
  );
  return elasticsearchDao.search(searchRequest, qb);
}
 
Example 13
Source Project: metron   Source File: ElasticsearchMetaAlertSearchDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SearchResponse getAllMetaAlertsForAlert(String guid) throws InvalidSearchException, IOException {
  if (guid == null || guid.trim().isEmpty()) {
    throw new InvalidSearchException("Guid cannot be empty");
  }
  // Searches for all alerts containing the meta alert guid in it's "metalerts" array
  QueryBuilder qb = boolQuery()
      .must(
          nestedQuery(
              MetaAlertConstants.ALERT_FIELD,
              boolQuery()
                  .must(termQuery(MetaAlertConstants.ALERT_FIELD + "." + GUID, guid)),
              ScoreMode.None
          ).innerHit(new InnerHitBuilder())
      )
      .must(termQuery(MetaAlertConstants.STATUS_FIELD, MetaAlertStatus.ACTIVE.getStatusString()));
  return queryAllResults(elasticsearchDao.getClient().getHighLevelClient(), qb, config.getMetaAlertIndex(),
      pageSize);
}
 
Example 14
Source Project: james-project   Source File: CriterionConverter.java    License: Apache License 2.0 6 votes vote down vote up
private void registerHeaderOperatorConverters() {

        registerHeaderOperatorConverter(
            SearchQuery.ExistsOperator.class,
            (headerName, operator) ->
                nestedQuery(JsonMessageConstants.HEADERS,
                    termQuery(JsonMessageConstants.HEADERS + "." + JsonMessageConstants.HEADER.NAME, headerName),
                    ScoreMode.Avg));
        
        registerHeaderOperatorConverter(
            SearchQuery.AddressOperator.class,
            (headerName, operator) -> manageAddressFields(headerName, operator.getAddress()));
        
        registerHeaderOperatorConverter(
            SearchQuery.DateOperator.class,
            (headerName, operator) -> dateRangeFilter(JsonMessageConstants.SENT_DATE, operator));
        
        registerHeaderOperatorConverter(
            SearchQuery.ContainsOperator.class,
            (headerName, operator) ->
                nestedQuery(JsonMessageConstants.HEADERS,
                    boolQuery()
                        .must(termQuery(JsonMessageConstants.HEADERS + "." + JsonMessageConstants.HEADER.NAME, headerName))
                        .must(matchQuery(JsonMessageConstants.HEADERS + "." + JsonMessageConstants.HEADER.VALUE, operator.getValue())),
                    ScoreMode.Avg));
    }
 
Example 15
@Test
void generateOneQueryRuleInCategorical_Entities() {
  Entity ref0 = new DynamicEntity(refEntityType);
  ref0.set(idAttrName, "id0");
  Entity ref1 = new DynamicEntity(refEntityType);
  ref1.set(idAttrName, "id1");
  Entity ref2 = new DynamicEntity(refEntityType);
  ref2.set(idAttrName, "id2");

  Iterable<Object> values = Arrays.asList(ref0, ref1, ref2);
  Query<Entity> q = new QueryImpl<>().in(categoricalAttrName, values);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      constantScoreQuery(
          nestedQuery(
              categoricalAttrName,
              termsQuery(
                  categoricalAttrName + '.' + idAttrName + '.' + FIELD_NOT_ANALYZED,
                  new Object[] {"id0", "id1", "id2"}),
              ScoreMode.Avg));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 16
@Test
void generateOneQueryRuleInMref_Entities() {
  Entity ref0 = new DynamicEntity(refEntityType);
  ref0.set(idAttrName, "id0");
  Entity ref1 = new DynamicEntity(refEntityType);
  ref1.set(idAttrName, "id1");
  Entity ref2 = new DynamicEntity(refEntityType);
  ref2.set(idAttrName, "id2");

  Iterable<Object> values = Arrays.asList(ref0, ref1, ref2);
  Query<Entity> q = new QueryImpl<>().in(mrefAttrName, values);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      constantScoreQuery(
          nestedQuery(
              mrefAttrName,
              termsQuery(
                  mrefAttrName + '.' + idAttrName + '.' + FIELD_NOT_ANALYZED,
                  new Object[] {"id0", "id1", "id2"}),
              ScoreMode.Avg));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 17
@Test
void generateOneQueryRuleInXref_Entities() {
  Entity ref0 = new DynamicEntity(refEntityType);
  ref0.set(idAttrName, "id0");
  Entity ref1 = new DynamicEntity(refEntityType);
  ref1.set(idAttrName, "id1");
  Entity ref2 = new DynamicEntity(refEntityType);
  ref2.set(idAttrName, "id2");

  Iterable<Object> values = Arrays.asList(ref0, ref1, ref2);
  Query<Entity> q = new QueryImpl<>().in(xrefAttrName, values);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      constantScoreQuery(
          nestedQuery(
              xrefAttrName,
              termsQuery(
                  xrefAttrName + '.' + idAttrName + '.' + FIELD_NOT_ANALYZED,
                  new Object[] {"id0", "id1", "id2"}),
              ScoreMode.Avg));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 18
@Test
void generateOneQueryRuleNotEqualsCategoricalNull() {
  String value = null;
  Query<Entity> q = new QueryImpl<>().not().eq(categoricalAttrName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      boolQuery()
          .mustNot(
              constantScoreQuery(
                  boolQuery()
                      .mustNot(
                          nestedQuery(
                              categoricalAttrName,
                              existsQuery(categoricalAttrName + ".xid"),
                              ScoreMode.Avg))));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 19
@Test
void testNestedQueryBuilderSizeTwo() {
  EntityType entityType = when(mock(EntityType.class).getIndexingDepth()).thenReturn(1).getMock();
  String parentFieldName = "parent";
  String childFieldName = "child";
  String queryValue = "value";
  QueryBuilder queryBuilder = termQuery(parentFieldName + '.' + childFieldName, queryValue);

  Attribute parentAttribute = mock(Attribute.class);
  when(documentIdGenerator.generateId(parentAttribute)).thenReturn(parentFieldName);
  Attribute childAttribute = mock(Attribute.class);
  when(documentIdGenerator.generateId(childAttribute)).thenReturn(childFieldName);
  QueryBuilder nestedQueryBuilder =
      queryGenerator.nestedQueryBuilder(
          entityType, asList(parentAttribute, childAttribute), queryBuilder);

  QueryBuilder expectedQueryBuilder =
      QueryBuilders.nestedQuery(
          parentFieldName,
          termQuery(parentFieldName + '.' + childFieldName, queryValue),
          ScoreMode.Avg);
  assertQueryBuilderEquals(nestedQueryBuilder, expectedQueryBuilder);
}
 
Example 20
Source Project: elasticsearch-sql   Source File: HasChildQueryParser.java    License: MIT License 5 votes vote down vote up
@Override
public AtomicQuery parse(ElasticsearchParser.HasChildClauseContext expression) {
    String type = expression.type.getText();
    BoolExpressionParser  boolExpressionParser=new BoolExpressionParser();
    QueryBuilder queryBuilder = boolExpressionParser.parseBoolQueryExpr(expression.query);
    QueryBuilder hasChildQueryBuilder=JoinQueryBuilders.hasChildQuery(type,queryBuilder, ScoreMode.Avg);
    AtomicQuery atomicQuery= new AtomicQuery(hasChildQueryBuilder);
    atomicQuery.getHighlighter().addAll(boolExpressionParser.highlighter);
    return atomicQuery;
}
 
Example 21
@Test
void generateOneQueryRuleLikeCompoundPartString() {
  String value = "value";
  Query<Entity> q = new QueryImpl<>().like(PREFIX + refCompoundPart0AttributeName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      QueryBuilders.nestedQuery(
          REF_ENTITY_ATT,
          QueryBuilders.matchPhrasePrefixQuery(PREFIX + refCompoundPart0AttributeName, value)
              .slop(10)
              .analyzer(DEFAULT_ANALYZER),
          ScoreMode.Avg);
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 22
@Test
public void shouldReturnBooksForGivenBucketUsingTemplate() {

    template.deleteIndex(Book.class);
    template.createIndex(Book.class);
    template.putMapping(Book.class);
    template.refresh(Book.class);

    Book book1 = new Book(RandomUtil.randomString(5, 10), "test1", System.currentTimeMillis());
    Book book2 = new Book(RandomUtil.randomString(5, 10), "test2", System.currentTimeMillis());

    Map<Integer, Collection<String>> map1 = new HashMap<>();
    map1.put(1, Arrays.asList("test1", "test2"));

    Map<Integer, Collection<String>> map2 = new HashMap<>();
    map2.put(1, Arrays.asList("test3", "test4"));

    book1.setBuckets(map1);
    book2.setBuckets(map2);

    repository.saveAll(Arrays.asList(book1, book2));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.Total))
        .build();

    Page<Book> books = repository.search(searchQuery);

    Assertions.assertThat(books.getContent()).hasSize(1);
}
 
Example 23
@Test
public void shouldReturnBooksForGivenBucketUsingTemplate() {

    template.deleteIndex(Book.class);
    template.createIndex(Book.class);
    template.putMapping(Book.class);
    template.refresh(Book.class);

    Book book1 = new Book(RandomUtil.randomString(5, 10), "test1", System.currentTimeMillis());
    Book book2 = new Book(RandomUtil.randomString(5, 10), "test2", System.currentTimeMillis());

    Map<Integer, Collection<String>> map1 = new HashMap<>();
    map1.put(1, Arrays.asList("test1", "test2"));

    Map<Integer, Collection<String>> map2 = new HashMap<>();
    map2.put(1, Arrays.asList("test3", "test4"));

    book1.setBuckets(map1);
    book2.setBuckets(map2);

    repository.saveAll(Arrays.asList(book1, book2));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.Total))
        .build();

    Page<Book> books = repository.search(searchQuery);

    Assertions.assertThat(books.getContent()).hasSize(1);
}
 
Example 24
private NestedQueryBuilder detectorIdQuery(SearchMappingsRequest searchMappingsRequest) {
    return QueryBuilders.nestedQuery(PercolatorDetectorMapping.DETECTOR_KEYWORD,
            QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery(
                    PercolatorDetectorMapping.DETECTOR_KEYWORD + "." + PercolatorDetectorMapping.DETECTOR_ID_KEYWORD,
                    searchMappingsRequest.getDetectorUuid().toString())),
            ScoreMode.None);
}
 
Example 25
private NestedQueryBuilder userIdQuery(SearchMappingsRequest searchMappingsRequest) {
    return QueryBuilders.nestedQuery(PercolatorDetectorMapping.USER_KEYWORD,
            QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery(
                    PercolatorDetectorMapping.USER_KEYWORD + "." + PercolatorDetectorMapping.USER_ID_KEYWORD,
                    searchMappingsRequest.getUserId())),
            ScoreMode.None);
}
 
Example 26
/**
 * Add query or nested query depending on the provided field.
 * if the field name contains a dot "." then we should extract the index name
 *
 * @param parameter query parameters
 * @param function  a supplier that defines the query that will be added
 * @return an instance of {@link NativeSearchQueryBuilder}
 */
private NativeSearchQueryBuilder getQuery(QueryParameter parameter,
                                          Supplier<AbstractQueryBuilder> function) {

  if (StringUtils.contains(parameter.getField(), DOT)) {
    String indexName = StringUtils.substringBeforeLast(parameter.getField(), DOT);
    return searchQuery.withQuery(nestedQuery(indexName, function.get(), ScoreMode.None));
  } else {
    return searchQuery.withQuery(function.get());
  }

}
 
Example 27
@Test
void generateOneQueryRuleLesserInt() {
  Integer value = 1;
  Query<Entity> q = new QueryImpl<>().lt(PREFIX + refIntAttributeName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      constantScoreQuery(
          nestedQuery(
              REF_ENTITY_ATT, rangeQuery(PREFIX + refIntAttributeName).lt(value), ScoreMode.Avg));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 28
Source Project: Stargraph   Source File: ElasticSearchQueryGenerator.java    License: MIT License 5 votes vote down vote up
@Override
public SearchQueryHolder findPropertyInstances(ModifiableSearchParams searchParams) {
    QueryBuilder queryBuilder = boolQuery()
            .should(nestedQuery("hyponyms",
                    matchQuery("hyponyms.word", searchParams.getSearchTerm()), ScoreMode.Max))
            .should(nestedQuery("hypernyms",
                    matchQuery("hypernyms.word", searchParams.getSearchTerm()), ScoreMode.Max))
            .should(nestedQuery("synonyms",
                    matchQuery("synonyms.word", searchParams.getSearchTerm()), ScoreMode.Max))
            .minimumNumberShouldMatch(1);

    return new ElasticQueryHolder(queryBuilder, searchParams);
}
 
Example 29
@Test
void generateOneQueryRuleLesserEqualDecimal() {
  Double value = 1.23;
  Query<Entity> q = new QueryImpl<>().le(PREFIX + refDecimalAttributeName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      constantScoreQuery(
          nestedQuery(
              REF_ENTITY_ATT,
              rangeQuery(PREFIX + refDecimalAttributeName).lte(value),
              ScoreMode.Avg));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example 30
@Test
void generateOneQueryRuleRangeInt() {
  Integer low = 3;
  Integer high = 9;
  Query<Entity> q = new QueryImpl<>().rng(PREFIX + refIntAttributeName, low, high);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      constantScoreQuery(
          nestedQuery(
              REF_ENTITY_ATT,
              rangeQuery(PREFIX + refIntAttributeName).gte(3).lte(9),
              ScoreMode.Avg));
  assertQueryBuilderEquals(expectedQuery, query);
}