org.apache.lucene.search.PrefixQuery Java Examples

The following examples show how to use org.apache.lucene.search.PrefixQuery. 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: DocumentUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static BooleanQuery createFQNQuery(final String resourceName) {
    String pkgName;
    String sName;
    int index = resourceName.lastIndexOf(BinaryName.PKG_SEPARATOR);
    if (index < 0) {
        pkgName = "";       //NOI18N
        sName = resourceName;
    } else {
        pkgName = resourceName.substring(0, index);
        sName = resourceName.substring(index+1);
    }
    final BooleanQuery snQuery = new BooleanQuery();
    snQuery.add (new WildcardQuery (new Term (DocumentUtil.FIELD_BINARY_NAME, sName + DocumentUtil.WILDCARD_QUERY_WILDCARD)),Occur.SHOULD);
    snQuery.add (new PrefixQuery (new Term (DocumentUtil.FIELD_BINARY_NAME, sName + '$')),Occur.SHOULD);   //NOI18N
    if (pkgName.length() == 0) {
        return snQuery;
    }
    final BooleanQuery fqnQuery = new BooleanQuery();
    fqnQuery.add(new TermQuery(new Term(DocumentUtil.FIELD_PACKAGE_NAME,pkgName)), Occur.MUST);
    fqnQuery.add(snQuery, Occur.MUST);
    return fqnQuery;
}
 
Example #2
Source File: TestHighlightingMatcher.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testWildcardCombinations() throws Exception {

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

    try (Monitor monitor = newMonitor()) {
      monitor.register(new MonitorQuery("1", bq));

      MatchingQueries<HighlightsMatch> matches = monitor.match(buildDoc("term1 term22 term4"), HighlightsMatch.MATCHER);
      HighlightsMatch m = matches.matches("1");
      assertNotNull(m);
      assertEquals(2, m.getHitCount());
    }

  }
 
Example #3
Source File: MtasSpanPrefixQuery.java    From mtas with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new mtas span prefix query.
 *
 * @param term the term
 * @param singlePosition the single position
 */
public MtasSpanPrefixQuery(Term term, boolean singlePosition) {
  super(singlePosition ? 1 : null, singlePosition ? 1 : null);
  PrefixQuery pfq = new PrefixQuery(term);
  query = new SpanMultiTermQueryWrapper<>(pfq);
  this.term = term;
  this.singlePosition = singlePosition;
  int i = term.text().indexOf(MtasToken.DELIMITER);
  if (i >= 0) {
    prefix = term.text().substring(0, i);
    value = term.text().substring((i + MtasToken.DELIMITER.length()));
    value = (value.length() > 0) ? value : null;
  } else {
    prefix = term.text();
    value = null;
  }
}
 
Example #4
Source File: LuceneMessageSearchIndex.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void update(MailboxId mailboxId, MessageUid uid, Flags f) throws IOException {
    try (IndexSearcher searcher = new IndexSearcher(IndexReader.open(writer, true))) {
        BooleanQuery query = new BooleanQuery();
        query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, mailboxId.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);

            doc.removeFields(FLAGS_FIELD);
            indexFlags(doc, f);

            writer.updateDocument(new Term(ID_FIELD, doc.get(ID_FIELD)), doc);
        }
    }
}
 
Example #5
Source File: TestUnifiedHighlighterMTQ.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testRussianPrefixQuery() throws IOException {
  Analyzer analyzer = new StandardAnalyzer();
  RandomIndexWriter iw = new RandomIndexWriter(random(), dir, analyzer);
  String field = "title";
  Document doc = new Document();
  doc.add(new Field(field, "я", fieldType)); // Russian char; uses 2 UTF8 bytes
  iw.addDocument(doc);
  IndexReader ir = iw.getReader();
  iw.close();

  IndexSearcher searcher = newSearcher(ir);
  Query query = new PrefixQuery(new Term(field, "я"));
  TopDocs topDocs = searcher.search(query, 1);
  UnifiedHighlighter highlighter = randomUnifiedHighlighter(searcher, analyzer);
  String[] snippets = highlighter.highlight(field, query, topDocs);
  assertEquals("[<b>я</b>]", Arrays.toString(snippets));
  ir.close();
}
 
Example #6
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 #7
Source File: LuceneQueryTranslator.java    From imhotep with Apache License 2.0 6 votes vote down vote up
public static Query rewrite(org.apache.lucene.search.Query q, Set<String> intFields) {
    if (q instanceof TermQuery) {
        return rewrite((TermQuery)q, intFields);
    } else if (q instanceof BooleanQuery) {
        return rewrite((BooleanQuery)q, intFields);
    } else if (q instanceof RangeQuery) {
        return rewrite((RangeQuery)q, intFields);
    } else if (q instanceof ConstantScoreRangeQuery) {
        return rewrite((ConstantScoreRangeQuery)q, intFields);
    } else if (q instanceof PrefixQuery) {
        return rewrite((PrefixQuery)q, intFields);
    } else if (q instanceof PhraseQuery) {
        return rewrite((PhraseQuery)q, intFields);
    }
    throw new IllegalArgumentException("unsupported lucene query type: " + q.getClass().getSimpleName());
}
 
Example #8
Source File: PrefixConditionTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testString() {

    Map<String, ColumnMapper> map = new HashMap<>();
    map.put("name", new ColumnMapperString());
    Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName());

    PrefixCondition prefixCondition = new PrefixCondition(0.5f, "name", "tr");
    Query query = prefixCondition.query(mappers);

    Assert.assertNotNull(query);
    Assert.assertEquals(PrefixQuery.class, query.getClass());
    PrefixQuery luceneQuery = (PrefixQuery) query;
    Assert.assertEquals("name", luceneQuery.getField());
    Assert.assertEquals("tr", luceneQuery.getPrefix().text());
    Assert.assertEquals(0.5f, query.getBoost(), 0);
}
 
Example #9
Source File: PrefixConditionTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testInetV4() {

    Map<String, ColumnMapper> map = new HashMap<>();
    map.put("name", new ColumnMapperInet());
    Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName());

    PrefixCondition wildcardCondition = new PrefixCondition(0.5f, "name", "192.168.");
    Query query = wildcardCondition.query(mappers);

    Assert.assertNotNull(query);
    Assert.assertEquals(PrefixQuery.class, query.getClass());
    PrefixQuery luceneQuery = (PrefixQuery) query;
    Assert.assertEquals("name", luceneQuery.getField());
    Assert.assertEquals("192.168.", luceneQuery.getPrefix().text());
    Assert.assertEquals(0.5f, query.getBoost(), 0);
}
 
Example #10
Source File: PrefixConditionTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testInetV6() {

    Map<String, ColumnMapper> map = new HashMap<>();
    map.put("name", new ColumnMapperInet());
    Schema mappers = new Schema(map, null, EnglishAnalyzer.class.getName());

    PrefixCondition wildcardCondition = new PrefixCondition(0.5f, "name", "2001:db8:2de:0:0:0:0:e");
    Query query = wildcardCondition.query(mappers);

    Assert.assertNotNull(query);
    Assert.assertEquals(PrefixQuery.class, query.getClass());
    PrefixQuery luceneQuery = (PrefixQuery) query;
    Assert.assertEquals("name", luceneQuery.getField());
    Assert.assertEquals("2001:db8:2de:0:0:0:0:e", luceneQuery.getPrefix().text());
    Assert.assertEquals(0.5f, query.getBoost(), 0);
}
 
Example #11
Source File: TestUnifiedHighlighterStrictPhrases.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Test it does *not* highlight the same term's not next to the span-near.  "charlie" in this case.
 * This particular example exercises "Rewrite" plus "MTQ" in the same query.
 */
public void testRewriteAndMtq() throws IOException {
  indexWriter.addDocument(newDoc("alpha bravo charlie - charlie bravo alpha"));
  initReaderSearcherHighlighter();

  SpanNearQuery snq = new SpanNearQuery(
      new SpanQuery[]{
          new SpanTermQuery(new Term("body", "bravo")),
          new SpanMultiTermQueryWrapper<>(new PrefixQuery(new Term("body", "ch")))}, // REWRITES
      0, true);

  BooleanQuery query = new BooleanQuery.Builder()
      .add(snq, BooleanClause.Occur.MUST)
      .add(new PrefixQuery(new Term("body", "al")), BooleanClause.Occur.MUST) // MTQ
      .add(newPhraseQuery("body", "alpha bravo"), BooleanClause.Occur.MUST)
      // add queries for other fields; we shouldn't highlight these because of that.
      .add(newPhraseQuery("title", "bravo alpha"), BooleanClause.Occur.SHOULD)
      .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[]{"<b>alpha bravo</b> <b>charlie</b> - charlie bravo <b>alpha</b>"}, snippets);
  } else {
    assertArrayEquals(new String[]{"<b>alpha</b> <b>bravo</b> <b>charlie</b> - charlie bravo <b>alpha</b>"}, snippets);
  }

  // do again, this time with MTQ disabled.  We should only find "alpha bravo".
  highlighter = new UnifiedHighlighter(searcher, indexAnalyzer);
  highlighter.setHandleMultiTermQuery(false);//disable but leave phrase processing enabled

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

  assertArrayEquals(new String[]{"<b>alpha</b> <b>bravo</b> charlie - charlie bravo alpha"},
      snippets);
}
 
Example #12
Source File: HighlighterTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testGetBestFragmentsMultiTerm() throws Exception {
  TestHighlightRunner helper = new TestHighlightRunner() {

    @Override
    public void run() throws Exception {
      numHighlights = 0;
      BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();
      booleanQuery.add(new TermQuery(new Term(FIELD_NAME, "john")), Occur.SHOULD);
      PrefixQuery prefixQuery = new PrefixQuery(new Term(FIELD_NAME, "kenn"));
      prefixQuery.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
      booleanQuery.add(prefixQuery, Occur.SHOULD);

      doSearching(booleanQuery.build());
      doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this);
      assertTrue("Failed to find correct number of highlights " + numHighlights + " found",
          numHighlights == 5);
    }
  };

  helper.start();
}
 
Example #13
Source File: TestSpanMultiTermQueryWrapper.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testNoSuchMultiTermsInSpanFirst() throws Exception {
  //this hasn't been a problem  
  FuzzyQuery fuzzyNoSuch = new FuzzyQuery(new Term("field", "noSuch"), 1, 0, 1, false);
  SpanQuery spanNoSuch = new SpanMultiTermQueryWrapper<>(fuzzyNoSuch);
  SpanQuery spanFirst = new SpanFirstQuery(spanNoSuch, 10);
 
  assertEquals(0, searcher.count(spanFirst));
  
  WildcardQuery wcNoSuch = new WildcardQuery(new Term("field", "noSuch*"));
  SpanQuery spanWCNoSuch = new SpanMultiTermQueryWrapper<>(wcNoSuch);
  spanFirst = new SpanFirstQuery(spanWCNoSuch, 10);
  assertEquals(0, searcher.count(spanFirst));

  RegexpQuery rgxNoSuch = new RegexpQuery(new Term("field", "noSuch"));
  SpanQuery spanRgxNoSuch = new SpanMultiTermQueryWrapper<>(rgxNoSuch);
  spanFirst = new SpanFirstQuery(spanRgxNoSuch, 10);
  assertEquals(0, searcher.count(spanFirst));
  
  PrefixQuery prfxNoSuch = new PrefixQuery(new Term("field", "noSuch"));
  SpanQuery spanPrfxNoSuch = new SpanMultiTermQueryWrapper<>(prfxNoSuch);
  spanFirst = new SpanFirstQuery(spanPrfxNoSuch, 10);
  assertEquals(0, searcher.count(spanFirst));
}
 
Example #14
Source File: QueryHelper.java    From fess with Apache License 2.0 6 votes vote down vote up
protected QueryBuilder convertPrefixQuery(final QueryContext context, final PrefixQuery prefixQuery, final float boost) {
    final String field = getSearchField(context, prefixQuery.getField());
    if (Constants.DEFAULT_FIELD.equals(field)) {
        context.addFieldLog(field, prefixQuery.getPrefix().text());
        return buildDefaultQueryBuilder((f, b) -> QueryBuilders.matchPhrasePrefixQuery(f,
                toLowercaseWildcard(prefixQuery.getPrefix().text())).boost(b * boost));
    } else if (isSearchField(field)) {
        context.addFieldLog(field, prefixQuery.getPrefix().text());
        if (notAnalyzedFieldSet.contains(field)) {
            return QueryBuilders.prefixQuery(field, toLowercaseWildcard(prefixQuery.getPrefix().text())).boost(boost);
        } else {
            return QueryBuilders.matchPhrasePrefixQuery(field, toLowercaseWildcard(prefixQuery.getPrefix().text())).boost(boost);
        }
    } else {
        final String query = prefixQuery.getPrefix().toString();
        final String origQuery = toLowercaseWildcard(query);
        context.addFieldLog(Constants.DEFAULT_FIELD, query);
        context.addHighlightedQuery(origQuery);
        return buildDefaultQueryBuilder((f, b) -> QueryBuilders.matchPhrasePrefixQuery(f, origQuery).boost(b * boost));
    }
}
 
Example #15
Source File: TestSpans.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testSpanNotWithMultiterm() throws Exception {
  SpanQuery q = spanNotQuery(
      spanTermQuery(field, "r1"),
      new SpanMultiTermQueryWrapper<>(new PrefixQuery(new Term(field, "s1"))),3,3);
  checkHits(q,  new int[] {14});

  q = spanNotQuery(
      spanTermQuery(field, "r1"),
      new SpanMultiTermQueryWrapper<>(new FuzzyQuery(new Term(field, "s12"), 1, 2)),3,3);
  checkHits(q,  new int[] {14});

  q = spanNotQuery(
      new SpanMultiTermQueryWrapper<>(new PrefixQuery(new Term(field, "r"))),
      spanTermQuery(field, "s21"),3,3);
  checkHits(q,  new int[] {13});


}
 
Example #16
Source File: TestSpanMultiTermQueryWrapper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrappedQueryIsNotModified() {
  final PrefixQuery pq = new PrefixQuery(new Term("field", "test"));
  int pqHash = pq.hashCode();
  SpanMultiTermQueryWrapper<PrefixQuery> wrapper = new SpanMultiTermQueryWrapper<>(pq);
  assertEquals(pqHash, pq.hashCode());
  wrapper.setRewriteMethod(new SpanMultiTermQueryWrapper.SpanRewriteMethod() {
    @Override
    public SpanQuery rewrite(IndexReader reader, MultiTermQuery query) throws IOException {
      return null;
    }
  });
  assertEquals(pqHash, pq.hashCode());
}
 
Example #17
Source File: MyCrazyCustomField.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Query getPrefixQuery(QParser parser, SchemaField sf, String termStr) {
  if(termStr.equals("foo")) {
    termStr = "bar";
  } else if (termStr.equals("bar")) {
    termStr = "foo";
  }

  PrefixQuery query = new PrefixQuery(new Term(sf.getName(), termStr));
  query.setRewriteMethod(sf.getType().getRewriteMethod(parser, sf));
  return query;
}
 
Example #18
Source File: TestSpanMultiTermQueryWrapper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testNoSuchMultiTermsInOr() throws Exception {
  //test to make sure non existent multiterms aren't throwing null pointer exceptions  
  FuzzyQuery fuzzyNoSuch = new FuzzyQuery(new Term("field", "noSuch"), 1, 0, 1, false);
  SpanQuery spanNoSuch = new SpanMultiTermQueryWrapper<>(fuzzyNoSuch);
  SpanQuery term = new SpanTermQuery(new Term("field", "brown"));
  SpanOrQuery near = new SpanOrQuery(new SpanQuery[]{term, spanNoSuch});
  assertEquals(1, searcher.count(near));
  
  //flip
  near = new SpanOrQuery(new SpanQuery[]{spanNoSuch, term});
  assertEquals(1, searcher.count(near));

  
  WildcardQuery wcNoSuch = new WildcardQuery(new Term("field", "noSuch*"));
  SpanQuery spanWCNoSuch = new SpanMultiTermQueryWrapper<>(wcNoSuch);
  near = new SpanOrQuery(new SpanQuery[]{term, spanWCNoSuch});
  assertEquals(1, searcher.count(near));

  RegexpQuery rgxNoSuch = new RegexpQuery(new Term("field", "noSuch"));
  SpanQuery spanRgxNoSuch = new SpanMultiTermQueryWrapper<>(rgxNoSuch);
  near = new SpanOrQuery(new SpanQuery[]{term, spanRgxNoSuch});
  assertEquals(1, searcher.count(near));
  
  PrefixQuery prfxNoSuch = new PrefixQuery(new Term("field", "noSuch"));
  SpanQuery spanPrfxNoSuch = new SpanMultiTermQueryWrapper<>(prfxNoSuch);
  near = new SpanOrQuery(new SpanQuery[]{term, spanPrfxNoSuch});
  assertEquals(1, searcher.count(near));
  
  near = new SpanOrQuery(new SpanQuery[]{spanPrfxNoSuch});
  assertEquals(0, searcher.count(near));
  
  near = new SpanOrQuery(new SpanQuery[]{spanPrfxNoSuch, spanPrfxNoSuch});
  assertEquals(0, searcher.count(near));

}
 
Example #19
Source File: StringFieldType.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Query prefixQuery(String value, MultiTermQuery.RewriteMethod method, QueryShardContext context) {
    failIfNotIndexed();
    PrefixQuery query = new PrefixQuery(new Term(name(), indexedValueForSearch(value)));
    if (method != null) {
        query.setRewriteMethod(method);
    }
    return query;
}
 
Example #20
Source File: TestSpanMultiTermQueryWrapper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testNoSuchMultiTermsInNotNear() throws Exception {
  //test to make sure non existent multiterms aren't throwing non-matching field exceptions  
  FuzzyQuery fuzzyNoSuch = new FuzzyQuery(new Term("field", "noSuch"), 1, 0, 1, false);
  SpanQuery spanNoSuch = new SpanMultiTermQueryWrapper<>(fuzzyNoSuch);
  SpanQuery term = new SpanTermQuery(new Term("field", "brown"));
  SpanNotQuery notNear = new SpanNotQuery(term, spanNoSuch, 0,0);
  assertEquals(1, searcher.count(notNear));

  //flip
  notNear = new SpanNotQuery(spanNoSuch, term, 0,0);
  assertEquals(0, searcher.count(notNear));
  
  //both noSuch
  notNear = new SpanNotQuery(spanNoSuch, spanNoSuch, 0,0);
  assertEquals(0, searcher.count(notNear));

  WildcardQuery wcNoSuch = new WildcardQuery(new Term("field", "noSuch*"));
  SpanQuery spanWCNoSuch = new SpanMultiTermQueryWrapper<>(wcNoSuch);
  notNear = new SpanNotQuery(term, spanWCNoSuch, 0,0);
  assertEquals(1, searcher.count(notNear));

  RegexpQuery rgxNoSuch = new RegexpQuery(new Term("field", "noSuch"));
  SpanQuery spanRgxNoSuch = new SpanMultiTermQueryWrapper<>(rgxNoSuch);
  notNear = new SpanNotQuery(term, spanRgxNoSuch, 1, 1);
  assertEquals(1, searcher.count(notNear));
  
  PrefixQuery prfxNoSuch = new PrefixQuery(new Term("field", "noSuch"));
  SpanQuery spanPrfxNoSuch = new SpanMultiTermQueryWrapper<>(prfxNoSuch);
  notNear = new SpanNotQuery(term, spanPrfxNoSuch, 1, 1);
  assertEquals(1, searcher.count(notNear));
  
}
 
Example #21
Source File: LuceneMessageSearchIndex.java    From james-project with Apache License 2.0 5 votes vote down vote up
private List<SearchResult> searchMultimap(Collection<MailboxId> mailboxIds, SearchQuery searchQuery) throws MailboxException {
    ImmutableList.Builder<SearchResult> results = ImmutableList.builder();

    Query inMailboxes = buildQueryFromMailboxes(mailboxIds);
    
    try (IndexSearcher searcher = new IndexSearcher(IndexReader.open(writer, true))) {
        BooleanQuery query = new BooleanQuery();
        query.add(inMailboxes, BooleanClause.Occur.MUST);
        // Not return flags documents
        query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST_NOT);

        List<Criterion> crits = searchQuery.getCriteria();
        for (Criterion crit : crits) {
            query.add(createQuery(crit, inMailboxes, searchQuery.getRecentMessageUids()), BooleanClause.Occur.MUST);
        }

        // query for all the documents sorted as specified in the SearchQuery
        TopDocs docs = searcher.search(query, null, maxQueryResults, createSort(searchQuery.getSorts()));
        ScoreDoc[] sDocs = docs.scoreDocs;
        for (ScoreDoc sDoc : sDocs) {
            Document doc = searcher.doc(sDoc.doc);
            MessageUid uid = MessageUid.of(Long.parseLong(doc.get(UID_FIELD)));
            MailboxId mailboxId = mailboxIdFactory.fromString(doc.get(MAILBOX_ID_FIELD));
            Optional<MessageId> messageId = toMessageId(Optional.ofNullable(doc.get(MESSAGE_ID_FIELD)));
            results.add(new SearchResult(messageId, mailboxId, uid));
        }
    } catch (IOException e) {
        throw new MailboxException("Unable to search the mailbox", e);
    }
    return results.build();
}
 
Example #22
Source File: LuceneMessageSearchIndex.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * This method will return the right {@link Query} depending if {@link #suffixMatch} is enabled
 */
private Query createTermQuery(String fieldName, String value) {
    if (suffixMatch) {
        return new WildcardQuery(new Term(fieldName, "*" + value + "*"));
    } else {
        return new PrefixQuery(new Term(fieldName, value));
    }
}
 
Example #23
Source File: LuceneMessageSearchIndex.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link Query} which is build based on the given {@link SearchQuery.AllCriterion}
 */
private Query createAllQuery(SearchQuery.AllCriterion crit) throws UnsupportedSearchException {
    BooleanQuery query = new BooleanQuery();
    
    query.add(createQuery(MessageRange.all()), BooleanClause.Occur.MUST);
    query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST_NOT);
    
    return query;
}
 
Example #24
Source File: QueryAttributes.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public boolean setCategoryTree( String categoryTree ){
	if ( categoryTree == null || categoryTree.length() == 0 )
		return false;

	Query catTreeQuery = new PrefixQuery(new Term(DocumentWrap.CATEGORYTREE, categoryTree));
	this.query = combineQueries(this.query, catTreeQuery);
	return true;
}
 
Example #25
Source File: LuceneQueryTranslator.java    From imhotep with Apache License 2.0 5 votes vote down vote up
public static Query rewrite(PrefixQuery pq, Set<String> intFields) {
    if (intFields.contains(pq.getPrefix().field())) {
        // not really sure what to do here, for now just treat it as an inequality query
        return Query.newRangeQuery(pq.getPrefix().field(), Long.parseLong(pq.getPrefix().text()), Long.MAX_VALUE, true);
    } else {
        final String prefix = pq.getPrefix().text();
        final String endTerm = prefix.substring(0, prefix.length() - 1) + ((char)((prefix.charAt(prefix.length() - 1) + 1)));
        return Query.newRangeQuery(pq.getPrefix().field(), prefix, endTerm, false);
    }
}
 
Example #26
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public static void assertEqualsQuery(Query expected, Query actual) {
  assertEquals(expected.getClass(), actual.getClass());
  if (expected instanceof BooleanQuery) {
    assertEqualsBooleanQuery((BooleanQuery) expected, (BooleanQuery) actual);
  } else if (expected instanceof SuperQuery) {
    assertEqualsSuperQuery((SuperQuery) expected, (SuperQuery) actual);
  } else if (expected instanceof TermQuery) {
    assertEqualsTermQuery((TermQuery) expected, (TermQuery) actual);
  } else if (expected instanceof PrefixQuery) {
    assertEqualsPrefixQuery((PrefixQuery) expected, (PrefixQuery) actual);
  } else if (expected instanceof WildcardQuery) {
    assertEqualsWildcardQuery((WildcardQuery) expected, (WildcardQuery) actual);
  } else if (expected instanceof FuzzyQuery) {
    assertEqualsFuzzyQuery((FuzzyQuery) expected, (FuzzyQuery) actual);
  } else if (expected instanceof RegexpQuery) {
    assertEqualsRegexpQuery((RegexpQuery) expected, (RegexpQuery) actual);
  } else if (expected instanceof TermRangeQuery) {
    assertEqualsTermRangeQuery((TermRangeQuery) expected, (TermRangeQuery) actual);
  } else if (expected instanceof MatchAllDocsQuery) {
    assertEqualsMatchAllDocsQuery((MatchAllDocsQuery) expected, (MatchAllDocsQuery) actual);
  } else if (expected instanceof MultiPhraseQuery) {
    assertEqualsMultiPhraseQuery((MultiPhraseQuery) expected, (MultiPhraseQuery) actual);
  } else if (expected instanceof PhraseQuery) {
    assertEqualsPhraseQuery((PhraseQuery) expected, (PhraseQuery) actual);
  } else if (expected instanceof NumericRangeQuery<?>) {
    assertEqualsNumericRangeQuery((NumericRangeQuery<?>) expected, (NumericRangeQuery<?>) actual);
  } else {
    fail("Type [" + expected.getClass() + "] not supported");
  }
}
 
Example #27
Source File: QueryHelper.java    From fess with Apache License 2.0 5 votes vote down vote up
protected QueryBuilder convertQuery(final QueryContext context, final Query query, final float boost) {
    if (query instanceof TermQuery) {
        return convertTermQuery(context, (TermQuery) query, boost);
    } else if (query instanceof TermRangeQuery) {
        return convertTermRangeQuery(context, (TermRangeQuery) query, boost);
    } else if (query instanceof PhraseQuery) {
        return convertPhraseQuery(context, (PhraseQuery) query, boost);
    } else if (query instanceof FuzzyQuery) {
        return convertFuzzyQuery(context, (FuzzyQuery) query, boost);
    } else if (query instanceof PrefixQuery) {
        return convertPrefixQuery(context, (PrefixQuery) query, boost);
    } else if (query instanceof WildcardQuery) {
        return convertWildcardQuery(context, (WildcardQuery) query, boost);
    } else if (query instanceof BooleanQuery) {
        final BooleanQuery booleanQuery = (BooleanQuery) query;
        return convertBooleanQuery(context, booleanQuery, boost);
    } else if (query instanceof MatchAllDocsQuery) {
        return QueryBuilders.matchAllQuery();
    } else if (query instanceof BoostQuery) {
        final BoostQuery boostQuery = (BoostQuery) query;
        return convertQuery(context, boostQuery.getQuery(), boostQuery.getBoost());
    }
    throw new InvalidQueryException(messages -> messages.addErrorsInvalidQueryUnknown(UserMessages.GLOBAL_PROPERTY_KEY), "Unknown q: "
            + query.getClass() + " => " + query);
}
 
Example #28
Source File: LuceneInMemorySearchIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPrefixQueryWhenFetchedDocumentThenCorrect() {
    InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
    inMemoryLuceneIndex.indexDocument("article", "Lucene introduction");
    inMemoryLuceneIndex.indexDocument("article", "Introduction to Lucene");

    Term term = new Term("body", "intro");
    Query query = new PrefixQuery(term);

    List<Document> documents = inMemoryLuceneIndex.searchIndex(query);
    Assert.assertEquals(2, documents.size());
}
 
Example #29
Source File: LuceneQueryTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrefixQuery() throws Exception {
    // 前缀查询
    PrefixQuery query = new PrefixQuery(new Term("title", "Touc"));
    TopDocs search = searcher.search(query, 1000);
    Assert.assertEquals(2, search.totalHits.value);
}
 
Example #30
Source File: TestHighlightingMatcher.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testDisjunctionMaxQuery() throws IOException {
  final DisjunctionMaxQuery query = new DisjunctionMaxQuery(Arrays.asList(
      new TermQuery(new Term(FIELD, "term1")), new PrefixQuery(new Term(FIELD, "term2"))
  ), 1.0f);

  try (Monitor monitor = newMonitor()) {
    monitor.register(new MonitorQuery("1", query));
    MatchingQueries<HighlightsMatch> matches = monitor.match(buildDoc("term1 term2 term3"), HighlightsMatch.MATCHER);
    HighlightsMatch m = matches.matches("1");
    assertNotNull(m);
    assertEquals(2, m.getHitCount());
  }

}