Java Code Examples for org.apache.lucene.search.BooleanClause

The following examples show how to use org.apache.lucene.search.BooleanClause. 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
Source Project: incubator-retired-blur   Source File: SuperParser.java    License: 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 2
Source Project: inception   Source File: MtasDocumentIndex.java    License: 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 Project: Elasticsearch   Source File: MultiMatchQueryBuilder.java    License: 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 4
Source Project: lucene-solr   Source File: MoreLikeThisHandler.java    License: 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 5
Source Project: yes-cart   Source File: SearchQueryFactoryImpl.java    License: 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 6
Source Project: lucene-solr   Source File: MoreLikeThisHandler.java    License: 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 7
@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 8
Source Project: incubator-atlas   Source File: BooleanQueryExpression.java    License: 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 9
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 10
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
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 12
Source Project: james-project   Source File: LuceneMessageSearchIndex.java    License: 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 13
Source Project: dremio-oss   Source File: LuceneQueryConverter.java    License: 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 14
Source Project: querqy   Source File: DismaxSearchEngineRequestAdapter.java    License: 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 15
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 16
Source Project: solr-redis   Source File: TestBooleanQueryExtractor.java    License: 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 17
Source Project: lucene-solr   Source File: TestQueryBuilder.java    License: 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 18
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 19
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 20
Source Project: lucene-solr   Source File: TestMinHashQParser.java    License: 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
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 22
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 23
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 24
Source Project: lucene-solr   Source File: TestQueryParser.java    License: 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 25
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 26
Source Project: lucene-solr   Source File: TestFunctionRangeQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTwoRangeQueries() throws IOException {
  Query rq1 = new FunctionRangeQuery(INT_VALUESOURCE, 2, 4, true, true);
  Query rq2 = new FunctionRangeQuery(INT_VALUESOURCE, 8, 10, true, true);
  Query bq = new BooleanQuery.Builder()
      .add(rq1, BooleanClause.Occur.SHOULD)
      .add(rq2, BooleanClause.Occur.SHOULD)
      .build();

  ScoreDoc[] scoreDocs = indexSearcher.search(bq, N_DOCS).scoreDocs;
  expectScores(scoreDocs, 10, 9, 8, 4, 3, 2);
}
 
Example 27
Source Project: lucene-solr   Source File: TestHighlightingMatcher.java    License: Apache License 2.0 5 votes vote down vote up
public void testWildcardBooleanRewrites() throws Exception {

    final Query wc = new PrefixQuery(new Term(FIELD, "term1"));

    final Query wrapper = new BooleanQuery.Builder()
        .add(wc, BooleanClause.Occur.MUST)
        .build();

    final Query wrapper2 = new BooleanQuery.Builder()
        .add(wrapper, BooleanClause.Occur.MUST)
        .build();

    final BooleanQuery bq = new BooleanQuery.Builder()
        .add(new PrefixQuery(new Term(FIELD, "term2")), BooleanClause.Occur.MUST)
        .add(wrapper2, BooleanClause.Occur.MUST_NOT)
        .build();

    try (Monitor monitor = new Monitor(ANALYZER)) {

      monitor.register(new MonitorQuery("1", bq));
      MatchingQueries<HighlightsMatch> matches = monitor.match(buildDoc("term2 term"), HighlightsMatch.MATCHER);
      HighlightsMatch m = matches.matches("1");
      assertNotNull(m);
      assertEquals(1, m.getHitCount());

      matches = monitor.match(buildDoc("term2 term"), HighlightsMatch.MATCHER);
      m = matches.matches("1");
      assertNotNull(m);
      assertEquals(1, m.getHitCount());
    }
  }
 
Example 28
Source Project: yes-cart   Source File: KeywordProductSearchQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Query createKeywordQueryExact(final String term) {

    final String escapedTerm = escapeValue(term);

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

    // product name weight (3)
    query.add(createTermQuery(PRODUCT_NAME_FIELD, escapedTerm, 3f), BooleanClause.Occur.SHOULD);
    query.add(createTermQuery(PRODUCT_DISPLAYNAME_FIELD, escapedTerm, 3f), BooleanClause.Occur.SHOULD);

    // product brand weight (5) must be higher than name (e.g. "hp notebook" must show hp brand first)
    query.add(createTermQuery(BRAND_FIELD_SEARCH, escapedTerm, 5f), BooleanClause.Occur.SHOULD);

    // category name weight (5~2) higher then name as names sometimes contains fuzzy terms (e.g. "notebook with usb")
    query.add(createFuzzyQuery(PRODUCT_CATEGORYNAME_FIELD, escapedTerm, 2, 5f), BooleanClause.Occur.SHOULD);

    // product type weight (7~2) higher then name and category for searching general type products (e.g. "usb stick")
    query.add(createFuzzyQuery(PRODUCT_TYPE_FIELD_SEARCH, escapedTerm, 2, 7f), BooleanClause.Occur.SHOULD);

    // product code matches (10) so that exact code match brings top result
    query.add(createTermQuery(PRODUCT_CODE_FIELD_SEARCH, escapedTerm,  10f), BooleanClause.Occur.SHOULD);
    query.add(createTermQuery(PRODUCT_MANUFACTURER_CODE_FIELD_SEARCH, escapedTerm, 10f), BooleanClause.Occur.SHOULD);
    query.add(createTermQuery(SKU_PRODUCT_CODE_FIELD_SEARCH, escapedTerm, 10f), BooleanClause.Occur.SHOULD);
    query.add(createTermQuery(SKU_PRODUCT_MANUFACTURER_CODE_FIELD_SEARCH, escapedTerm, 10f), BooleanClause.Occur.SHOULD);

    // attribute primary (10)
    query.add(createTermQuery(ATTRIBUTE_VALUE_SEARCHPRIMARY_FIELD, escapedTerm, 10f), BooleanClause.Occur.SHOULD);

    // attribute general (4/2~1)
    query.add(createTermQuery(ATTRIBUTE_VALUE_SEARCHPHRASE_FIELD, escapedTerm, 4f), BooleanClause.Occur.SHOULD);
    query.add(createFuzzyQuery(ATTRIBUTE_VALUE_SEARCHPHRASE_FIELD, escapedTerm, 1, 2f), BooleanClause.Occur.SHOULD);

    return query.build();

}
 
Example 29
Source Project: lucene-solr   Source File: HandyQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public Query getQuery(Element e) throws ParserException {
  final BooleanQuery.Builder bq = new BooleanQuery.Builder();
  final Query lhsQ = getSubQuery(e, "Left");
  final Query rhsQ = getSubQuery(e, "Right");
  bq.add(new BooleanClause(lhsQ, BooleanClause.Occur.SHOULD));
  bq.add(new BooleanClause(rhsQ, BooleanClause.Occur.SHOULD));
  return bq.build();
}
 
Example 30
Source Project: lucene-solr   Source File: TestQueryParser.java    License: Apache License 2.0 5 votes vote down vote up
public void testDefaultSplitOnWhitespace() throws Exception {
  QueryParser parser = new QueryParser("field", new Analyzer1());

  assertFalse(parser.getSplitOnWhitespace()); // default is false

  // A multi-word synonym source will form a synonym query for the same-starting-position tokens
  TermQuery guinea = new TermQuery(new Term("field", "guinea"));
  TermQuery pig = new TermQuery(new Term("field", "pig"));
  TermQuery cavy = new TermQuery(new Term("field", "cavy"));

  // A multi-word synonym source will form a graph query for synonyms that formed the graph token stream
  BooleanQuery.Builder synonym = new BooleanQuery.Builder();
  synonym.add(guinea, BooleanClause.Occur.MUST);
  synonym.add(pig, BooleanClause.Occur.MUST);
  BooleanQuery guineaPig = synonym.build();

  BooleanQuery graphQuery = new BooleanQuery.Builder()
      .add(new BooleanQuery.Builder()
          .add(guineaPig, BooleanClause.Occur.SHOULD)
          .add(cavy, BooleanClause.Occur.SHOULD)
          .build(), BooleanClause.Occur.SHOULD)
      .build();
  assertEquals(graphQuery, parser.parse("guinea pig"));

  boolean oldSplitOnWhitespace = splitOnWhitespace;
  splitOnWhitespace = QueryParser.DEFAULT_SPLIT_ON_WHITESPACE;
  assertQueryEquals("guinea pig", new MockSynonymAnalyzer(), "((+guinea +pig) cavy)");
  splitOnWhitespace = oldSplitOnWhitespace;
}