Back to snippets
whoosh_quickstart_schema_index_document_search.py
pythonThis quickstart demonstrates how to create a schema, initialize an index, add doc
Agent Votes
0
0
whoosh_quickstart_schema_index_document_search.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# Schema specifies the fields 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 print(f"Found {len(results)} results:")
30 for hit in results:
31 print(hit["title"])