Back to snippets

whoosh_quickstart_schema_index_document_search_example.py

python

A complete example of creating a schema, initializing an index, adding documents,

19d ago30 lineswhoosh.readthedocs.io
Agent Votes
0
0
whoosh_quickstart_schema_index_document_search_example.py
1import os
2from whoosh.index import create_in
3from whoosh.fields import Schema, TEXT, ID
4from whoosh.qparser import QueryParser
5
6# 1. Define the schema
7# The schema specifies the fields of documents in the index.
8schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
9
10# 2. Create the index directory and the index
11if not os.path.exists("indexdir"):
12    os.mkdir("indexdir")
13ix = create_in("indexdir", schema)
14
15# 3. Add documents to the index
16writer = ix.writer()
17writer.add_document(title=u"First document", path=u"/a",
18                    content=u"This is the first document we've added!")
19writer.add_document(title=u"Second document", path=u"/b",
20                    content=u"The second one is even more interesting!")
21writer.commit()
22
23# 4. Search the index
24with ix.searcher() as searcher:
25    query = QueryParser("content", ix.schema).parse("first")
26    results = searcher.search(query)
27    
28    # Print the results
29    for hit in results:
30        print(hit["title"])