PyLucene 3.4.0-1 import
[pylucene.git] / samples / LuceneInAction / lia / searching / PhraseQueryTest.py
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
5 #
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
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 # ====================================================================
14
15 from unittest import TestCase
16
17 from lucene import \
18      WhitespaceAnalyzer, Document, Field, IndexWriter, Term, \
19      IndexSearcher, PhraseQuery, RAMDirectory
20
21
22 class PhraseQueryTest(TestCase):
23
24     def setUp(self):
25
26         # set up sample document
27         directory = RAMDirectory()
28         writer = IndexWriter(directory, WhitespaceAnalyzer(), True,
29                              IndexWriter.MaxFieldLength.UNLIMITED)
30         doc = Document()
31         doc.add(Field("field", "the quick brown fox jumped over the lazy dog",
32                        Field.Store.YES, Field.Index.ANALYZED))
33         writer.addDocument(doc)
34         writer.close()
35
36         self.searcher = IndexSearcher(directory)
37
38     def matched(self, phrase, slop):
39
40         query = PhraseQuery()
41         query.setSlop(slop)
42
43         for word in phrase:
44             query.add(Term("field", word))
45
46         topDocs = self.searcher.search(query, 50)
47
48         return topDocs.totalHits > 0
49
50     def testSlopComparison(self):
51
52         phrase = ["quick", "fox"]
53
54         self.assert_(not self.matched(phrase, 0), "exact phrase not found")
55         self.assert_(self.matched(phrase, 1), "close enough")
56
57     def testReverse(self):
58
59         phrase = ["fox", "quick"]
60
61         self.assert_(not self.matched(phrase, 2), "hop flop")
62         self.assert_(self.matched(phrase, 3), "hop hop slop")
63
64     def testMultiple(self):
65
66         self.assert_(not self.matched(["quick", "jumped", "lazy"], 3),
67                      "not close enough")
68
69         self.assert_(self.matched(["quick", "jumped", "lazy"], 4),
70                      "just enough")
71
72         self.assert_(not self.matched(["lazy", "jumped", "quick"], 7),
73                      "almost but not quite")
74
75         self.assert_(self.matched(["lazy", "jumped", "quick"], 8),
76                      "bingo")