org.apache.lucene.search.BooleanClause Java Examples

The following examples show how to use org.apache.lucene.search.BooleanClause. 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: ExplorerQueryTests.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
public void testBooleanQuery() throws Exception {
    TermQuery tq1 = new TermQuery(new Term("text", "cow"));
    TermQuery tq2 = new TermQuery(new Term("text", "brown"));
    TermQuery tq3 = new TermQuery(new Term("text", "how"));

    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.add(tq1, BooleanClause.Occur.SHOULD);
    builder.add(tq2, BooleanClause.Occur.SHOULD);
    builder.add(tq3, BooleanClause.Occur.SHOULD);

    Query q = builder.build();
    String statsType = "sum_raw_tf";

    ExplorerQuery eq = new ExplorerQuery(q, statsType);

    // Verify tf score
    TopDocs docs = searcher.search(eq, 4);
    assertThat(docs.scoreDocs[0].score, equalTo(3.0f));
}
 
Example #2
Source File: MtasDocumentIndex.java    From inception with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a specific document from the index based on its timestamp
 * 
 * @param aSourceDocumentId
 *            The ID of the source document to be removed
 * @param aAnnotationDocumentId
 *            The ID of the annotation document to be removed
 * @param aUser
 *            The owner of the document to be removed
 * @param aTimestamp
 *            The timestamp of the document to be removed
 */
private void deindexDocument(long aSourceDocumentId, long aAnnotationDocumentId, String aUser,
        String aTimestamp)
    throws IOException
{
    log.debug(
            "Removing document from index in project [{}]({}). sourceId: {}, "
                    + "annotationId: {}, user: {}, timestamp: {}",
            project.getName(), project.getId(), aSourceDocumentId, aAnnotationDocumentId,
            aUser, aTimestamp);
    
    IndexWriter indexWriter = getIndexWriter();

    // Prepare boolean query with the two obligatory terms (id and timestamp)
    BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder()
            .add(new TermQuery(new Term(FIELD_ID,
                    String.format("%d/%d", aSourceDocumentId, aAnnotationDocumentId))),
                    BooleanClause.Occur.MUST)
            .add(new TermQuery(new Term(FIELD_TIMESTAMP, aTimestamp)),
                    BooleanClause.Occur.MUST);

    // Delete document based on the previous query
    indexWriter.deleteDocuments(booleanQuery.build());

    scheduleCommit();
}
 
Example #3
Source File: SuperParser.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
private String findFirstGroupName(Query query) {
  if (query instanceof BooleanQuery) {
    BooleanQuery booleanQuery = (BooleanQuery) query;
    for (BooleanClause clause : booleanQuery.clauses()) {
      String groupName = findFirstGroupName(clause.getQuery());
      if (groupName != null) {
        return groupName;
      }
    }
    return null;
  } else if (query instanceof SuperQuery) {
    SuperQuery sq = (SuperQuery) query;
    return findFirstGroupName(sq.getQuery());
  } else {
    String fieldName = _fieldNames.get(query);
    return getGroupName(fieldName);
  }
}
 
Example #4
Source File: LuceneQueryConverter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private Query toBooleanQuery(SearchQuery.Boolean booleanQuery) {
  final BooleanQuery.Builder builder = new BooleanQuery.Builder();
  final BooleanClause.Occur occur;
  switch(booleanQuery.getOp()) {
  case AND:
    occur = BooleanClause.Occur.MUST;
    break;
  case OR:
    occur = BooleanClause.Occur.SHOULD;
      break;
  default:
    throw new AssertionError("Unknown boolean operator: " + booleanQuery.getOp());
  }

  for(SearchQuery clause: booleanQuery.getClausesList()) {
    builder.add(toLuceneQuery(clause), occur);
  }
  return builder.build();
}
 
Example #5
Source File: TripleIndexCreatorContext.java    From AGDISTIS with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<Triple> search(String subject, String predicate, String object, int maxNumberOfResults) {
	BooleanQuery bq = new BooleanQuery();
	List<Triple> triples = new ArrayList<Triple>();
	try {
		if (subject != null && subject.equals("http://aksw.org/notInWiki")) {
			log.error(
					"A subject 'http://aksw.org/notInWiki' is searched in the index. That is strange and should not happen");
		}
		if (subject != null) {
			TermQuery tq = new TermQuery(new Term(FIELD_NAME_URI, subject));
			bq.add(tq, BooleanClause.Occur.MUST);
		}
		triples = getFromIndex(maxNumberOfResults, bq);
		if (triples == null) {
			return new ArrayList<Triple>();
		}

	} catch (Exception e) {
		log.error(e.getLocalizedMessage() + " -> " + subject);

	}
	return triples;
}
 
Example #6
Source File: DBPediaCandidateType.java    From uncc2014watsonsim with GNU General Public License v2.0 6 votes vote down vote up
public List<String> query(String question_text) {
	List<String> results = new ArrayList<>();
	try {
		BooleanQuery q = new BooleanQuery();
		for (String word : question_text.split("\\W+")) {
			q.add(new TermQuery(new Term("text", word)), BooleanClause.Occur.SHOULD);
			q.add(new TermQuery(new Term("text", word.toLowerCase())), BooleanClause.Occur.SHOULD);
		}
		TopDocs topDocs = searcher.search(q, 1);
		
		ScoreDoc[] hits = topDocs.scoreDocs;
		// This isn't range based because we need the rank
		for (int i=0; i < hits.length; i++) {
			ScoreDoc s = hits[i];
			Document doc = searcher.doc(s.doc);
			results.add(doc.get("uri"));
		}
	} catch (IOException e) {
		System.out.println("Failed to query Lucene. Is the index in the correct location?");
		e.printStackTrace();
	}
	return results;
}
 
Example #7
Source File: LuceneMessageSearchIndex.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Flags retrieveFlags(Mailbox mailbox, MessageUid uid) throws IOException {
    try (IndexSearcher searcher = new IndexSearcher(IndexReader.open(writer, true))) {
        Flags retrievedFlags = new Flags();

        BooleanQuery query = new BooleanQuery();
        query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, mailbox.getMailboxId().serialize())), BooleanClause.Occur.MUST);
        query.add(createQuery(MessageRange.one(uid)), BooleanClause.Occur.MUST);
        query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST);

        TopDocs docs = searcher.search(query, 100000);
        ScoreDoc[] sDocs = docs.scoreDocs;
        for (ScoreDoc sDoc : sDocs) {
            Document doc = searcher.doc(sDoc.doc);

            Stream.of(doc.getValues(FLAGS_FIELD))
                .forEach(flag -> fromString(flag).ifPresentOrElse(retrievedFlags::add, () -> retrievedFlags.add(flag)));
        }
        return retrievedFlags;
    }
}
 
Example #8
Source File: TestQueryParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testEnableGraphQueries() throws Exception {
  QueryParser dumb = new QueryParser("field", new Analyzer1());
  dumb.setSplitOnWhitespace(false);
  dumb.setEnableGraphQueries(false);
  
  TermQuery pig = new TermQuery(new Term("field", "pig"));

  // A multi-word synonym source will just form a boolean query when graph queries are disabled:
  Query inner = new SynonymQuery.Builder("field")
      .addTerm(new Term("field", "cavy"))
      .addTerm(new Term("field", "guinea"))
      .build();
  BooleanQuery.Builder b = new BooleanQuery.Builder();
  b.add(inner, BooleanClause.Occur.SHOULD);
  b.add(pig, BooleanClause.Occur.SHOULD);
  BooleanQuery query = b.build();
  assertEquals(query, dumb.parse("guinea pig"));
}
 
Example #9
Source File: ExplorerQueryTests.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
public void testQueryWithTermPositionMinWithTwoTerms() throws Exception {
    TermQuery tq1 = new TermQuery(new Term("text", "stop"));
    TermQuery tq2 = new TermQuery(new Term("text", "hip-hop"));
    TermQuery tq3 = new TermQuery(new Term("text", "monkeys"));

    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.add(tq1, BooleanClause.Occur.SHOULD);
    builder.add(tq2, BooleanClause.Occur.SHOULD);
    builder.add(tq3, BooleanClause.Occur.SHOULD);

    Query q = builder.build();
    String statsType = "min_raw_tp";

    ExplorerQuery eq = new ExplorerQuery(q, statsType);

    // Verify score is 5 (5 unique terms)
    TopDocs docs = searcher.search(eq, 4);

    assertThat(docs.scoreDocs[0].score, equalTo(3.0f));
}
 
Example #10
Source File: AlfrescoSolrTrackerStateIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Acl createAndIndexSomeAclData() throws Exception
{
    AclChangeSet aclChangeSet = getAclChangeSet(1);

    Acl acl = getAcl(aclChangeSet);
    Acl acl2 = getAcl(aclChangeSet);

    AclReaders aclReaders = getAclReaders(aclChangeSet, acl, singletonList("joel"), singletonList("phil"), null);
    AclReaders aclReaders2 = getAclReaders(aclChangeSet, acl2, singletonList("jim"), singletonList("phil"), null);

    indexAclChangeSet(aclChangeSet, asList(acl, acl2), asList(aclReaders, aclReaders2));

    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.add(new BooleanClause(new TermQuery(new Term(QueryConstants.FIELD_SOLR4_ID, "TRACKER!STATE!ACLTX")), BooleanClause.Occur.MUST));
    builder.add(new BooleanClause(LegacyNumericRangeQuery.newLongRange(QueryConstants.FIELD_S_ACLTXID, aclChangeSet.getId(), aclChangeSet.getId() + 1, true, false), BooleanClause.Occur.MUST));
    BooleanQuery waitForQuery = builder.build();
    waitForDocCount(waitForQuery, 1, MAX_WAIT_TIME);

    return acl;
}
 
Example #11
Source File: DismaxSearchEngineRequestAdapter.java    From querqy with Apache License 2.0 6 votes vote down vote up
@Override
public Query applyMinimumShouldMatch(final BooleanQuery query) {

    final List<BooleanClause> clauses = query.clauses();
    if (clauses.size() < 2) {
        return query;
    }

    for (final BooleanClause clause : clauses) {
        if ((clause.getQuery() instanceof BooleanQuery) && (clause.getOccur() != BooleanClause.Occur.MUST)) {
            return query; // seems to be a complex query with sub queries - do not
            // apply mm
        }
    }

    return SolrPluginUtils.setMinShouldMatch(query, minShouldMatch);

}
 
Example #12
Source File: MultiMatchQueryBuilder.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public Query combineGrouped(List<Query> queries) {
    if (queries == null || queries.isEmpty()) {
        return null;
    }
    if (queries.size() == 1) {
        return queries.get(0);
    }
    if (groupDismax) {
        return new DisjunctionMaxQuery(queries, tieBreaker);
    } else {
        BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();
        for (Query query : queries) {
            booleanQuery.add(query, BooleanClause.Occur.SHOULD);
        }
        return booleanQuery.build();
    }
}
 
Example #13
Source File: TestUnifiedHighlighterStrictPhrases.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testMaxLen() throws IOException {
  indexWriter.addDocument(newDoc("alpha bravo charlie - gap alpha bravo")); // hyphen is at char 21
  initReaderSearcherHighlighter();
  highlighter.setMaxLength(21);

  BooleanQuery query = new BooleanQuery.Builder()
      .add(newPhraseQuery("body", "alpha bravo"), BooleanClause.Occur.SHOULD)
      .add(newPhraseQuery("body", "gap alpha"), BooleanClause.Occur.SHOULD)
      .add(newPhraseQuery("body", "charlie gap"), BooleanClause.Occur.SHOULD)
      .build();

  TopDocs topDocs = searcher.search(query, 10, Sort.INDEXORDER);
  String[] snippets = highlighter.highlight("body", query, topDocs);

  final boolean weightMatches = highlighter.getFlags("body").contains(HighlightFlag.WEIGHT_MATCHES);
  if (fieldType == UHTestHelper.reanalysisType || weightMatches) {
    if (weightMatches) {
      assertArrayEquals(new String[]{"<b>alpha bravo</b> charlie -"}, snippets);
    } else {
      assertArrayEquals(new String[]{"<b>alpha</b> <b>bravo</b> charlie -"}, snippets);
    }
  } else {
    assertArrayEquals(new String[]{"<b>alpha</b> <b>bravo</b> <b>charlie</b> -"}, snippets);
  }
}
 
Example #14
Source File: TestBooleanQueryExtractor.java    From solr-redis with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtractTwoSubqueryFields() {
  Query q1 = new TermQuery(new Term("field1", "value1"));
  Query q2 = new TermQuery(new Term("field2", "value2"));
  
  BooleanQuery.Builder builder = new BooleanQuery.Builder();
  builder.add(new BooleanClause(q1, BooleanClause.Occur.MUST));
  builder.add(new BooleanClause(q2, BooleanClause.Occur.MUST));
  BooleanQuery booleanQuery = builder.build();
  BooleanQueryExtractor booleanQueryExtractor = new BooleanQueryExtractor();

  Set<String> extractedFieldNames = new HashSet<>();

  booleanQueryExtractor.extractSubQueriesFields(booleanQuery, DEFAULT_EXTRACTORS, extractedFieldNames);
  assertEquals(2, extractedFieldNames.size());
  assertTrue(extractedFieldNames.contains("field1"));
  assertTrue(extractedFieldNames.contains("field2"));
}
 
Example #15
Source File: MoreLikeThisHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private Query getBoostedQuery(Query mltquery) {
  BooleanQuery boostedQuery = (BooleanQuery)mltquery;
  if (boostFields.size() > 0) {
    BooleanQuery.Builder newQ = new BooleanQuery.Builder();
    newQ.setMinimumNumberShouldMatch(boostedQuery.getMinimumNumberShouldMatch());
    for (BooleanClause clause : boostedQuery) {
      Query q = clause.getQuery();
      float originalBoost = 1f;
      if (q instanceof BoostQuery) {
        BoostQuery bq = (BoostQuery) q;
        q = bq.getQuery();
        originalBoost = bq.getBoost();
      }
      Float fieldBoost = boostFields.get(((TermQuery) q).getTerm().field());
      q = ((fieldBoost != null) ? new BoostQuery(q, fieldBoost * originalBoost) : clause.getQuery());
      newQ.add(q, clause.getOccur());
    }
    boostedQuery = newQ.build();
  }
  return boostedQuery;
}
 
Example #16
Source File: SearchQueryFactoryImpl.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
private Query join(final List<Query> allQueries, final Query extraQuery, BooleanClause.Occur with) {

        if (CollectionUtils.isEmpty(allQueries)) {
            if (extraQuery != null) {
                return extraQuery;
            }
            return null;
        }

        final BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();

        for (final Query query : allQueries) {
            booleanQuery.add(query, with);
        }

        if (extraQuery != null) {
            booleanQuery.add(extraQuery, with);
        }

        return booleanQuery.build();

    }
 
Example #17
Source File: ExplorerQueryTests.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
public void testQueryWithTermPositionAvgWithTwoTerms() throws Exception {
    TermQuery tq1 = new TermQuery(new Term("text", "stop"));
    TermQuery tq2 = new TermQuery(new Term("text", "hip-hop"));
    TermQuery tq3 = new TermQuery(new Term("text", "monkeys"));

    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.add(tq1, BooleanClause.Occur.SHOULD);
    builder.add(tq2, BooleanClause.Occur.SHOULD);
    builder.add(tq3, BooleanClause.Occur.SHOULD);

    Query q = builder.build();
    String statsType = "avg_raw_tp";

    ExplorerQuery eq = new ExplorerQuery(q, statsType);

    // Verify score is 5 (5 unique terms)
    TopDocs docs = searcher.search(eq, 4);

    assertThat(docs.scoreDocs[0].score, equalTo(5.0f));
}
 
Example #18
Source File: MoreLikeThisHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public DocListAndSet getMoreLikeThis( int id, int start, int rows, List<Query> filters, List<InterestingTerm> terms, int flags ) throws IOException
{
  Document doc = reader.document(id);
  rawMLTQuery = mlt.like(id);
  boostedMLTQuery = getBoostedQuery( rawMLTQuery );
  if( terms != null ) {
    fillInterestingTermsFromMLTQuery( boostedMLTQuery, terms );
  }

  // exclude current document from results
  BooleanQuery.Builder realMLTQuery = new BooleanQuery.Builder();
  realMLTQuery.add(boostedMLTQuery, BooleanClause.Occur.MUST);
  realMLTQuery.add(
      new TermQuery(new Term(uniqueKeyField.getName(), uniqueKeyField.getType().storedToIndexed(doc.getField(uniqueKeyField.getName())))), 
        BooleanClause.Occur.MUST_NOT);
  this.realMLTQuery = realMLTQuery.build();
  
  DocListAndSet results = new DocListAndSet();
  if (this.needDocSet) {
    results = searcher.getDocListAndSet(this.realMLTQuery, filters, null, start, rows, flags);
  } else {
    results.docList = searcher.getDocList(this.realMLTQuery, filters, null, start, rows, flags);
  }
  return results;
}
 
Example #19
Source File: TestUnifiedHighlighterStrictPhrases.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testSubPhrases() throws IOException {
  indexWriter.addDocument(newDoc("alpha bravo charlie - charlie bravo alpha"));
  initReaderSearcherHighlighter();

  BooleanQuery query = new BooleanQuery.Builder()
      .add(newPhraseQuery("body", "alpha bravo charlie"), BooleanClause.Occur.MUST)
      .add(newPhraseQuery("body", "alpha bravo"), BooleanClause.Occur.MUST)
      .build();

  TopDocs topDocs = searcher.search(query, 10, Sort.INDEXORDER);
  dupMatchAllowed.set(false); // We don't want duplicates from both PhraseQuery
  String[] snippets = highlighter.highlight("body", query, topDocs);

  if (highlighter.getFlags("body").contains(HighlightFlag.WEIGHT_MATCHES)) {
    assertArrayEquals(new String[]{"<b>alpha bravo charlie</b> - charlie bravo alpha"}, snippets);
  } else {
    assertArrayEquals(new String[]{"<b>alpha</b> <b>bravo</b> <b>charlie</b> - charlie bravo alpha"}, snippets);
  }
}
 
Example #20
Source File: TestMinHashQParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testBandsWrap() throws SyntaxError {

  NamedList<Object> par = new NamedList<>();
  par.add("sim", "0.8");
  par.add("tp", "0.694");
  par.add("sep", ",");
  par.add("debug", "false");

  QParser qparser = h.getCore().getQueryPlugin("minhash").createParser("1, 2, 3, 4, 5, 6, 7, 8, 9, 10", SolrParams.toSolrParams(par), null, null);
  Query query = qparser.getQuery();

  BooleanQuery bq = (BooleanQuery)query;
  assertEquals(4, bq.clauses().size());
  for(BooleanClause clause : bq.clauses()) {
    assertEquals(3, ((BooleanQuery)((ConstantScoreQuery)clause.getQuery()).getQuery())  .clauses().size());
  }

}
 
Example #21
Source File: AlfrescoSolrFingerprintIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void prepare() throws Exception
{
    AclChangeSet aclChangeSet = getAclChangeSet(1);
    acl = getAcl(aclChangeSet);
    Acl acl2 = getAcl(aclChangeSet);

    AclReaders aclReaders = getAclReaders(aclChangeSet, acl, singletonList("joel"), singletonList("phil"), null);
    AclReaders aclReaders2 = getAclReaders(aclChangeSet, acl2, singletonList("jim"), singletonList("phil"), null);

    indexAclChangeSet(aclChangeSet,
            asList(acl, acl2),
            asList(aclReaders, aclReaders2));

    // Check for the ACL state stamp.
    BooleanQuery.Builder builder = new BooleanQuery.Builder();
    builder.add(new BooleanClause(new TermQuery(new Term(QueryConstants.FIELD_SOLR4_ID, "TRACKER!STATE!ACLTX")), BooleanClause.Occur.MUST));
    builder.add(new BooleanClause(LegacyNumericRangeQuery.newLongRange(QueryConstants.FIELD_S_ACLTXID, aclChangeSet.getId(), aclChangeSet.getId() + 1, true, false), BooleanClause.Occur.MUST));
    BooleanQuery waitForQuery = builder.build();
    waitForDocCount(waitForQuery, 1, MAX_WAIT_TIME);
}
 
Example #22
Source File: TestUnifiedHighlighterStrictPhrases.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testWithSameTermQuery() throws IOException {
  indexWriter.addDocument(newDoc("Yin yang, yin gap yang"));
  initReaderSearcherHighlighter();

  BooleanQuery query = new BooleanQuery.Builder()
      .add(new TermQuery(new Term("body", "yin")), BooleanClause.Occur.MUST)
      .add(newPhraseQuery("body", "yin yang"), BooleanClause.Occur.MUST)
      // add queries for other fields; we shouldn't highlight these because of that.
      .add(new TermQuery(new Term("title", "yang")), BooleanClause.Occur.SHOULD)
      .build();

  TopDocs topDocs = searcher.search(query, 10, Sort.INDEXORDER);
  dupMatchAllowed.set(false); // We don't want duplicates from "Yin" being in TermQuery & PhraseQuery.
  String[] snippets = highlighter.highlight("body", query, topDocs);
  if (highlighter.getFlags("body").contains(HighlightFlag.WEIGHT_MATCHES)) {
    assertArrayEquals(new String[]{"<b>Yin yang</b>, <b>yin</b> gap yang"}, snippets);
  } else {
    assertArrayEquals(new String[]{"<b>Yin</b> <b>yang</b>, <b>yin</b> gap yang"}, snippets);
  }
}
 
Example #23
Source File: TestUnifiedHighlighterStrictPhrases.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testBasics() throws IOException {
  indexWriter.addDocument(newDoc("Yin yang, filter")); // filter out. test getTermToSpanLists reader 1-doc filter
  indexWriter.addDocument(newDoc("yin alone, Yin yang, yin gap yang"));
  initReaderSearcherHighlighter();

  //query:  -filter +"yin yang"
  BooleanQuery query = new BooleanQuery.Builder()
      .add(new TermQuery(new Term("body", "filter")), BooleanClause.Occur.MUST_NOT)
      .add(newPhraseQuery("body", "yin yang"), BooleanClause.Occur.MUST)
      .build();


  TopDocs topDocs = searcher.search(query, 10, Sort.INDEXORDER);
  String[] snippets = highlighter.highlight("body", query, topDocs);
  if (highlighter.getFlags("body").contains(HighlightFlag.WEIGHT_MATCHES)) {
    assertArrayEquals(new String[]{"yin alone, <b>Yin yang</b>, yin gap yang"}, snippets);
  } else {
    assertArrayEquals(new String[]{"yin alone, <b>Yin</b> <b>yang</b>, yin gap yang"}, snippets);
  }
}
 
Example #24
Source File: TestQueryBuilder.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** more complex synonyms with default AND operator */
public void testCJKSynonymsAND2() throws Exception {
  BooleanQuery.Builder expected = new BooleanQuery.Builder();
  expected.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.MUST);
  SynonymQuery inner = new SynonymQuery.Builder("field")
      .addTerm(new Term("field", "国"))
      .addTerm(new Term("field", "國"))
      .build();
  expected.add(inner, BooleanClause.Occur.MUST);
  SynonymQuery inner2 = new SynonymQuery.Builder("field")
      .addTerm(new Term("field", "国"))
      .addTerm(new Term("field", "國"))
      .build();
  expected.add(inner2, BooleanClause.Occur.MUST);
  QueryBuilder builder = new QueryBuilder(new MockCJKSynonymAnalyzer());
  assertEquals(expected.build(), builder.createBooleanQuery("field", "中国国", BooleanClause.Occur.MUST));
}
 
Example #25
Source File: BooleanQueryExpression.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Override
public Pipe asPipe() {
    Map<BooleanClause.Occur, Collection<BooleanClause>> groupedClauses = groupClauses();

    Pipe andPipe = null;
    Collection<Pipe> andPipes = processAndClauses(groupedClauses);
    andPipes.addAll(processNotClauses(groupedClauses));
    if (! andPipes.isEmpty()) {
        andPipe = new AndFilterPipe(andPipes.toArray(new Pipe[andPipes.size()]));
    }

    Collection<Pipe> orPipes = processOrClauses(groupedClauses);
    if (! orPipes.isEmpty()) {
        if (andPipe != null) {
            orPipes.add(andPipe);
        }
        return new OrFilterPipe(orPipes.toArray(new Pipe[orPipes.size()]));
    } else {
        return andPipe;
    }
}
 
Example #26
Source File: TestMoreLikeThis.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testBoostFactor() throws Throwable {
  Map<String,Float> originalValues = getOriginalValues();
  mlt.setFieldNames(new String[] {"text"});
  mlt.setBoost(true);
  
  // this mean that every term boost factor will be multiplied by this
  // number
  float boostFactor = 5;
  mlt.setBoostFactor(boostFactor);
  
  BooleanQuery query = (BooleanQuery) mlt.like("text", new StringReader(
      "lucene release"));
  Collection<BooleanClause> clauses = query.clauses();
  
  assertEquals("Expected " + originalValues.size() + " clauses.",
      originalValues.size(), clauses.size());

  for (BooleanClause clause : clauses) {
    BoostQuery bq = (BoostQuery) clause.getQuery();
    TermQuery tq = (TermQuery) bq.getQuery();
    Float termBoost = originalValues.get(tq.getTerm().text());
    assertNotNull("Expected term " + tq.getTerm().text(), termBoost);

    float totalBoost = termBoost * boostFactor;
    assertEquals("Expected boost of " + totalBoost + " for term '"
        + tq.getTerm().text() + "' got " + bq.getBoost(), totalBoost, bq
        .getBoost(), 0.0001);
  }
}
 
Example #27
Source File: AnalyzingInfixSuggester.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private BooleanQuery toQuery(Set<BytesRef> contextInfo) {
  if (contextInfo == null || contextInfo.isEmpty()) {
    return null;
  }
  
  BooleanQuery.Builder contextFilter = new BooleanQuery.Builder();
  for (BytesRef context : contextInfo) {
    addContextToQuery(contextFilter, context, BooleanClause.Occur.SHOULD);
  }
  return contextFilter.build();
}
 
Example #28
Source File: ScoreOrderFragmentsBuilderTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void test3Frags() throws Exception {
  BooleanQuery.Builder query = new BooleanQuery.Builder();
  query.add(new TermQuery(new Term(F, "a")), BooleanClause.Occur.SHOULD);
  query.add(new TermQuery(new Term(F, "c")), BooleanClause.Occur.SHOULD);

  FieldFragList ffl = ffl(query.build(), "a b b b b b b b b b b b a b a b b b b b c a a b b" );
  ScoreOrderFragmentsBuilder sofb = new ScoreOrderFragmentsBuilder();
  String[] f = sofb.createFragments( reader, 0, F, ffl, 3 );
  assertEquals( 3, f.length );
  // check score order
  assertEquals( "<b>c</b> <b>a</b> <b>a</b> b b", f[0] );
  assertEquals( "b b <b>a</b> b <b>a</b> b b b b b c", f[1] );
  assertEquals( "<b>a</b> b b b b b b b b b b", f[2] );
}
 
Example #29
Source File: NotQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Query makeLuceneQueryFieldNoBoost(String fieldName, BasicQueryFactory qf) {
  List<Query> luceneSubQueries = makeLuceneSubQueriesField(fieldName, qf);
  BooleanQuery.Builder bq = new BooleanQuery.Builder();
  bq.add( luceneSubQueries.get(0), BooleanClause.Occur.MUST);
  SrndBooleanQuery.addQueriesToBoolean(bq,
          // FIXME: do not allow weights on prohibited subqueries.
          luceneSubQueries.subList(1, luceneSubQueries.size()),
          // later subqueries: not required, prohibited
          BooleanClause.Occur.MUST_NOT);
  return bq.build();
}
 
Example #30
Source File: PointVectorStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a query to retrieve documents that fully contain the input envelope.
 */
private Query makeWithin(Rectangle bbox) {
  BooleanQuery.Builder bq = new BooleanQuery.Builder();
  BooleanClause.Occur MUST = BooleanClause.Occur.MUST;
  if (bbox.getCrossesDateLine()) {
    //use null as performance trick since no data will be beyond the world bounds
    bq.add(rangeQuery(fieldNameX, null/*-180*/, bbox.getMaxX()), BooleanClause.Occur.SHOULD );
    bq.add(rangeQuery(fieldNameX, bbox.getMinX(), null/*+180*/), BooleanClause.Occur.SHOULD );
    bq.setMinimumNumberShouldMatch(1);//must match at least one of the SHOULD
  } else {
    bq.add(rangeQuery(fieldNameX, bbox.getMinX(), bbox.getMaxX()), MUST);
  }
  bq.add(rangeQuery(fieldNameY, bbox.getMinY(), bbox.getMaxY()), MUST);
  return bq.build();
}