0

I do not understand why the query does not work.

I need to search for a document in by two fields. Two ID-s. It need to search for a document if 2 values match. ID1 AND ID2

But I get an empty result.

        query = MultiFieldQueryParser.parse(new String[]{id1, id2},
            new String[]{"ID1", "ID2"},
            new SimpleAnalyzer());
        TopDocs topDocs = searcher.search(query, 1);
        Document doc = searcher.doc(topDocs.scoreDocs[0].doc)

The index works 100%. Verified by other requests.

Thanks for the help.

JDev
  • 2,157
  • 3
  • 31
  • 57
  • So are you attempting to search for two IDs in two different fields? Or a single id in two different fields? – MatsLindh Jul 04 '18 at 10:59
  • two different IDs in two different fields. I need match "ID1 AND ID2" – JDev Jul 04 '18 at 11:06
  • should id1 only match in the field id1 and id2 only in the field for id2? Or could they match in any of the fields? `ID1:id1 AND ID2:id2` vs `ID1:(id1 id2) ID2:(id1 id2)` vs `(ID1:id1 OR ID2:id1) AND (ID1:id2 OR ID2:id2)`? – MatsLindh Jul 04 '18 at 11:53
  • Yes. "id1 only match in the field id1 and id2 only in the field for id2". Thanks for the Help. – JDev Jul 04 '18 at 12:04

2 Answers2

1

Since you only want to perform an AND intersection between two separate queries -- and not really do a MultiFieldQuery (where you search for the same value in multiple fields), a slightly modified version of what is shown in Lucene OR search using Boolean Query should work:

BooleanQuery bothQuery = new BooleanQuery();

                                         // field, value
TermQuery idQuery1 = new TermQuery(new Term("ID1", "id1"));
TermQuery idQuery2 = new TermQuery(new Term("ID2", "id2"));

bothQuery.add(new BooleanClause(idQuery1, BooleanClause.Occur.MUST));
bothQuery.add(new BooleanClause(idQuery2, BooleanClause.Occur.MUST));

TopDocs topDocs = searcher.search(bothQuery, 1);
Document doc = searcher.doc(topDocs.scoreDocs[0].doc)
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
1

Thank MatsLindh for the above answer. Managed to solved similar problems for school assignment thanks to you.

Bear in mind that the sample code is outdated and for Lucene 8.9 (my case), you should do this instead

Query query = new BooleanQuery.Builder()
.add(query1, BooleanClause.Occur.MUST)
.add(query2, BooleanClause.Occur.MUST)
.build();
TopDocs topDocs = searcher.search(query, 1);
Document doc = searcher.doc(topDocs.scoreDocs[0].doc)

TermQuery objects and Query objects can be used interchangeably to replace query1 and query2 for the above code.

gway
  • 31
  • 3