PyLucene 3.4.0-1 import
[pylucene.git] / samples / LuceneInAction / lia / meetlucene / Searcher.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 import os
16
17 from time import time
18 from datetime import timedelta
19
20 from lucene import \
21      Document, IndexSearcher, FSDirectory, QueryParser, StandardAnalyzer, \
22      SimpleFSDirectory, File, Version
23
24
25 class Searcher(object):
26
27     def main(cls, argv):
28
29         if len(argv) != 3:
30             print "Usage: python Searcher.py <index dir> <query>"
31
32         else:
33             indexDir = argv[1]
34             q = argv[2]
35
36             if not (os.path.exists(indexDir) and os.path.isdir(indexDir)):
37                 raise IOError, "%s does not exist or is not a directory" %(indexDir)
38
39             cls.search(indexDir, q)
40
41     def search(cls, indexDir, q):
42
43         fsDir = SimpleFSDirectory(File(indexDir))
44         searcher = IndexSearcher(fsDir, True)
45
46         query = QueryParser(Version.LUCENE_CURRENT, "contents",
47                             StandardAnalyzer(Version.LUCENE_CURRENT)).parse(q)
48         start = time()
49         hits = searcher.search(query, 50).scoreDocs
50         duration = timedelta(seconds=time() - start)
51
52         print "Found %d document(s) (in %s) that matched query '%s':" %(len(hits), duration, q)
53
54         for hit in hits:
55             doc = searcher.doc(hit.doc)
56             print 'path:', doc.get("path")
57
58     main = classmethod(main)
59     search = classmethod(search)
60
61
62 if __name__ == "__main__":
63     import sys
64     Searcher.main(sys.argv)