1 # ====================================================================
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 # ====================================================================
15 from unittest import TestCase
17 WhitespaceAnalyzer, Document, Field, IndexWriter, Term, BooleanQuery, \
18 IndexSearcher, MultiPhraseQuery, PhraseQuery, RAMDirectory, BooleanClause
21 class MultiPhraseQueryTest(TestCase):
25 directory = RAMDirectory()
26 writer = IndexWriter(directory, WhitespaceAnalyzer(), True,
27 IndexWriter.MaxFieldLength.UNLIMITED)
30 doc1.add(Field("field", "the quick brown fox jumped over the lazy dog",
31 Field.Store.YES, Field.Index.ANALYZED))
32 writer.addDocument(doc1)
35 doc2.add(Field("field", "the fast fox hopped over the hound",
36 Field.Store.YES, Field.Index.ANALYZED))
37 writer.addDocument(doc2)
40 self.searcher = IndexSearcher(directory, True)
44 query = MultiPhraseQuery()
45 query.add([Term("field", "quick"),
46 Term("field", "fast")])
47 query.add(Term("field", "fox"))
50 topDocs = self.searcher.search(query, 10)
51 self.assertEqual(1, topDocs.totalHits, "fast fox match")
54 topDocs = self.searcher.search(query, 10)
55 self.assertEqual(2, topDocs.totalHits, "both match");
57 def testAgainstOR(self):
59 quickFox = PhraseQuery()
61 quickFox.add(Term("field", "quick"))
62 quickFox.add(Term("field", "fox"))
64 fastFox = PhraseQuery()
65 fastFox.add(Term("field", "fast"))
66 fastFox.add(Term("field", "fox"))
68 query = BooleanQuery()
69 query.add(quickFox, BooleanClause.Occur.SHOULD)
70 query.add(fastFox, BooleanClause.Occur.SHOULD)
71 topDocs = self.searcher.search(query, 10)
72 self.assertEqual(2, topDocs.totalHits)
74 def debug(self, hits):
77 print "%s: %s" %(hits.score(i), doc['field'])