3 import sys, os, lucene, threading, time
4 from datetime import datetime
7 This class is loosely based on the Lucene (java implementation) demo class
8 org.apache.lucene.demo.IndexFiles. It will take a directory as an argument
9 and will index all of the files in that directory and downward recursively.
10 It will index on the file path, the file name and the file contents. The
11 resulting Lucene index will be placed in the current directory and called
26 class IndexFiles(object):
27 """Usage: python IndexFiles <doc_directory>"""
29 def __init__(self, root, storeDir, analyzer):
31 if not os.path.exists(storeDir):
33 store = lucene.SimpleFSDirectory(lucene.File(storeDir))
34 writer = lucene.IndexWriter(store, analyzer, True,
35 lucene.IndexWriter.MaxFieldLength.LIMITED)
36 writer.setMaxFieldLength(1048576)
37 self.indexDocs(root, writer)
39 print 'optimizing index',
40 threading.Thread(target=ticker.run).start()
46 def indexDocs(self, root, writer):
47 for root, dirnames, filenames in os.walk(root):
48 for filename in filenames:
49 if not filename.endswith('.txt'):
51 print "adding", filename
53 path = os.path.join(root, filename)
55 contents = unicode(file.read(), 'iso-8859-1')
57 doc = lucene.Document()
58 doc.add(lucene.Field("name", filename,
59 lucene.Field.Store.YES,
60 lucene.Field.Index.NOT_ANALYZED))
61 doc.add(lucene.Field("path", path,
62 lucene.Field.Store.YES,
63 lucene.Field.Index.NOT_ANALYZED))
65 doc.add(lucene.Field("contents", contents,
66 lucene.Field.Store.NO,
67 lucene.Field.Index.ANALYZED))
69 print "warning: no content in %s" % filename
70 writer.addDocument(doc)
72 print "Failed in indexDocs:", e
74 if __name__ == '__main__':
76 print IndexFiles.__doc__
79 print 'lucene', lucene.VERSION
80 start = datetime.now()
82 IndexFiles(sys.argv[1], "index", lucene.StandardAnalyzer(lucene.Version.LUCENE_CURRENT))