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

The following examples show how to use org.apache.lucene.search.join.ScoreMode. 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: QueryClauseSearchGeneratorTest.java    From molgenis with GNU Lesser General Public License v3.0 7 votes vote down vote up
@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
Source File: NestedObjectTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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 #3
Source File: ESRequestMapper.java    From syncer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #4
Source File: QueryGeneratorIT.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: QueryGeneratorIT.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #6
Source File: ElasticsearchIndexer.java    From datashare with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #7
Source File: QueryGeneratorIT.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #8
Source File: ElasticsearchMetaAlertSearchDao.java    From metron with 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 #9
Source File: LoggingIT.java    From elasticsearch-learning-to-rank with 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 #10
Source File: QueryGeneratorIT.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: LoggingIT.java    From elasticsearch-learning-to-rank with 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 #12
Source File: CriterionConverter.java    From james-project with 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 #13
Source File: QueryGeneratorReferencesIT.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #14
Source File: BookRepositoryTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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 #15
Source File: NestedObjectTests.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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 #16
Source File: ElasticsearchMetaAlertSearchDao.java    From metron with 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 #17
Source File: BookRepositoryTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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 #18
Source File: QueryClauseSearchQueryGeneratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #19
Source File: BaseQueryClauseGeneratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 File: QueryGeneratorReferencesIT.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void generateMultipleQueryRule() {
  // query: ref.a or (b and ref.c)
  Boolean booleanValue = Boolean.TRUE;
  String stringValue = "str";
  Integer intValue = 1;
  Query<Entity> q =
      new QueryImpl<>()
          .eq(PREFIX + refBoolAttributeName, booleanValue)
          .or()
          .nest()
          .eq(stringAttributeName, stringValue)
          .and()
          .eq(PREFIX + refIntAttributeName, intValue)
          .unnest();
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder booleanQuery =
      constantScoreQuery(
          nestedQuery(
              REF_ENTITY_ATT,
              termQuery(PREFIX + refBoolAttributeName, booleanValue),
              ScoreMode.Avg));
  QueryBuilder stringQuery =
      constantScoreQuery(termQuery(stringAttributeName + '.' + FIELD_NOT_ANALYZED, stringValue));
  QueryBuilder intQuery =
      constantScoreQuery(
          nestedQuery(
              REF_ENTITY_ATT, termQuery(PREFIX + refIntAttributeName, intValue), ScoreMode.Avg));
  BoolQueryBuilder stringIntQuery = QueryBuilders.boolQuery().must(stringQuery).must(intQuery);
  QueryBuilder expectedQuery =
      QueryBuilders.boolQuery().should(booleanQuery).should(stringIntQuery).minimumShouldMatch(1);
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example #21
Source File: QueryGeneratorIT.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void generateOneQueryRuleNotEqualsCategorical() {
  String value = "id";
  Query<Entity> q = new QueryImpl<>().not().eq(categoricalAttrName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      boolQuery()
          .mustNot(
              constantScoreQuery(
                  nestedQuery(
                      categoricalAttrName,
                      termQuery(categoricalAttrName + ".xid." + FIELD_NOT_ANALYZED, value),
                      ScoreMode.Avg)));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example #22
Source File: QueryGeneratorReferencesIT.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void generateOneQueryRuleGreaterLong() {
  Long value = 1L;
  Query<Entity> q = new QueryImpl<>().gt(PREFIX + refLongAttributeName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      constantScoreQuery(
          nestedQuery(
              REF_ENTITY_ATT,
              rangeQuery(PREFIX + refLongAttributeName).gt(value),
              ScoreMode.Avg));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example #23
Source File: QueryGeneratorReferencesIT.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void generateOneQueryRuleNotEqualsEqualsBool() {
  Boolean value = Boolean.TRUE;
  Query<Entity> q = new QueryImpl<>().not().eq(PREFIX + refBoolAttributeName, value);
  QueryBuilder query = queryGenerator.createQueryBuilder(q, entityType);
  QueryBuilder expectedQuery =
      boolQuery()
          .mustNot(
              constantScoreQuery(
                  nestedQuery(
                      REF_ENTITY_ATT,
                      termQuery(PREFIX + refBoolAttributeName, value),
                      ScoreMode.Avg)));
  assertQueryBuilderEquals(expectedQuery, query);
}
 
Example #24
Source File: ElasticsearchTestBase.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testNestedEntities() throws Exception {
  createEntitiesDocument();
  ae.process(jCas);

  createEntitiesDocument2();
  ae.process(jCas);

  elasticsearch.flush(BALEEN_INDEX);

  assertEquals(new Long(2), getCount());

  SearchRequestBuilder srb =
      elasticsearch
          .client()
          .prepareSearch(BALEEN_INDEX)
          .setQuery(
              QueryBuilders.nestedQuery(
                  "entities",
                  QueryBuilders.boolQuery()
                      .must(QueryBuilders.matchQuery("entities.type", "Location"))
                      .must(QueryBuilders.matchQuery("entities.value", "London")),
                  ScoreMode.Avg));

  SearchHits results = elasticsearch.client().search(srb.request()).actionGet().getHits();
  assertEquals(1, results.getTotalHits());
}
 
Example #25
Source File: ScoreModeParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** 
 * recognizes as-is {@link ScoreMode} names, and lowercase as well, 
 * otherwise throws exception 
 * @throws SyntaxError when it's unable to parse
 * */
static ScoreMode parse(String score) throws SyntaxError {
  final ScoreMode scoreMode = lowerAndCapitalCase.get(score);
  if (scoreMode == null) {
    throw new SyntaxError("Unable to parse ScoreMode from: " + score);
  }
  return scoreMode;
}
 
Example #26
Source File: TestScoreJoinQPScore.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Ignore("SOLR-7814, also don't forget cover boost at testCacheHit()")
public void testBoost() throws Exception {
  indexDataForScorring();
  ScoreMode score = ScoreMode.values()[random().nextInt(ScoreMode.values().length)];

  final SolrQueryRequest req = req("q", "{!join from=movieId_s to=id score=" + score + " b=200}title:movie", "fl", "id,score", "omitHeader", "true");
  SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, new SolrQueryResponse()));
  final Query luceneQ = QParser.getParser(req.getParams().get("q"), req).getQuery().rewrite(req.getSearcher().getSlowAtomicReader());
  assertTrue(luceneQ instanceof BoostQuery);
  float boost = ((BoostQuery) luceneQ).getBoost();
  assertEquals("" + luceneQ, Float.floatToIntBits(200), Float.floatToIntBits(boost));
  SolrRequestInfo.clearRequestInfo();
  req.close();
}
 
Example #27
Source File: BJQParserTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testScoresForParent() throws Exception{
  final ArrayList<ScoreMode> noNone = new ArrayList<>(Arrays.asList(ScoreMode.values()));
  noNone.remove(ScoreMode.None);
  final String notNoneMode = (noNone.get(random().nextInt(noNone.size()))).name();
  
  String leastScore = getLeastScore("child_s:l");
  assertTrue(leastScore+" > 0.0", Float.parseFloat(leastScore)>0.0);
  final String notNoneLower = usually() ? notNoneMode: notNoneMode.toLowerCase(Locale.ROOT);
  
  assertQ(req("q", "{!parent which=\"parent_s:[* TO *]\" score="+notNoneLower+"}child_s:l","fl","score"),
      "//*[@numFound='6']","(//float[@name='score'])["+(random().nextInt(6)+1)+"]>='"+leastScore+"'");
}
 
Example #28
Source File: BJQParserTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testWrongScoreExceptionForParent() throws Exception {
  final String aMode = ScoreMode.values()[random().nextInt(ScoreMode.values().length)].name();
  final String wrongMode = rarely()? "":(rarely()? " ":
    rarely()? aMode.substring(1):aMode.toUpperCase(Locale.ROOT));
  assertQEx("wrong score mode", 
      req("q", "{!parent which=\"parent_s:[* TO *]\" score="+wrongMode+"}child_s:l","fl","score")
      , SolrException.ErrorCode.BAD_REQUEST.code);
}
 
Example #29
Source File: BJQFilterAccessibleTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testAbilityToCreateBJQfromAnotherPackage() throws IOException {
  try (SolrQueryRequest req = lrf.makeRequest()) {
    TermQuery childQuery = new TermQuery(new Term("child_s", "l"));
    Query parentQuery = new WildcardQuery(new Term("parent_s", "*"));
    ToParentBlockJoinQuery tpbjq = new ToParentBlockJoinQuery(childQuery,
        BlockJoinParentQParser.getCachedBitSetProducer(req,parentQuery), ScoreMode.Max);
    Assert.assertEquals(6, req.getSearcher().search(tpbjq,10).totalHits.value);
  }
}
 
Example #30
Source File: HasChildQueryParser.java    From elasticsearch-sql with 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;
}