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
18 WhitespaceAnalyzer, IndexSearcher, RAMDirectory, \
19 Document, Field, IndexWriter, TermQuery, SpanNearQuery
21 from lia.extsearch.queryparser.NumberUtils import NumberUtils
22 from lia.extsearch.queryparser.CustomQueryParser import \
23 MultiFieldCustomQueryParser, CustomQueryParser
26 class AdvancedQueryParserTest(TestCase):
30 self.analyzer = WhitespaceAnalyzer()
31 self.directory = RAMDirectory()
33 writer = IndexWriter(self.directory, self.analyzer, True,
34 IndexWriter.MaxFieldLength.LIMITED)
36 for i in xrange(1, 501):
38 doc.add(Field("id", NumberUtils.pad(i),
39 Field.Store.YES, Field.Index.NOT_ANALYZED))
40 writer.addDocument(doc)
44 def testCustomQueryParser(self):
46 parser = CustomQueryParser("field", self.analyzer)
50 self.fail("Wildcard queries should not be allowed")
56 parser.parse("xunit~")
57 self.fail("Fuzzy queries should not be allowed")
62 def testCustomMultiFieldQueryParser(self):
64 parser = MultiFieldCustomQueryParser(["field"], self.analyzer)
68 self.fail("Wildcard queries should not be allowed")
74 parser.parse("xunit~")
75 self.fail("Fuzzy queries should not be allowed")
80 def testIdRangeQuery(self):
82 parser = CustomQueryParser("field", self.analyzer)
84 query = parser.parse("id:[37 TO 346]")
85 self.assertEqual("id:[0000000037 TO 0000000346]",
86 query.toString("field"), "padded")
88 searcher = IndexSearcher(self.directory, True)
89 scoreDocs = searcher.search(query, 1000).scoreDocs
90 self.assertEqual(310, len(scoreDocs))
92 print parser.parse("special:[term TO *]")
93 print parser.parse("special:[* TO term]")
95 def testPhraseQuery(self):
97 parser = CustomQueryParser("field", self.analyzer)
99 query = parser.parse("singleTerm")
100 self.assert_(TermQuery.instance_(query), "TermQuery")
102 query = parser.parse("\"a phrase\"")
103 self.assert_(SpanNearQuery.instance_(query), "SpanNearQuery")