Introduction to RediSearch
RediSearch is a powerful search and indexing engine built as a Redis Module. It provides highly efficient full-text search, secondary indexing, and querying capabilities to Redis, making it an indispensable tool for developers looking to enhance their Redis capabilities.
Key Features of RediSearch
- Full-text search with advanced querying capabilities
- Secondary indexing and querying of multiple data types
- Optimized for performance with minimal overhead
Basic APIs and Code Snippets
Create an Index
FT.CREATE myIndex ON HASH PREFIX 1 doc: SCHEMA title TEXT WEIGHT 5.0 body TEXT url TEXT
Index a Document
HSET doc:1 title "Redisearch Introduction" body "Learn how to use Redisearch for full-text search capabilities" url "https://example.com/docs/redisearch"
Search the Index
FT.SEARCH myIndex "Redisearch"
Delete an Index
FT.DROPINDEX myIndex
Advanced API Examples
Creating a Complex Schema
FT.CREATE myIndex ON HASH PREFIX 1 doc: SCHEMA title TEXT WEIGHT 5.0 body TEXT url TAG SORTABLE
Performing a Fuzzy Search
FT.SEARCH myIndex "Red~"
Using Numeric Filters
FT.SEARCH myIndex "@price:[100 200]"
Tag Field Search
FT.SEARCH myIndex "@url:{http://example.com}"
Building a Simple Application with RediSearch
Let’s build a sample application to demonstrate the use of the APIs mentioned above.
Application Setup
import redis from redis.commands.search.field import TextField, NumericField, TagField from redis.commands.search.indexDefinition import IndexDefinition from redis.commands.search.client import SearchIndex client = redis.StrictRedis() # Create Index Definition schema = [ TextField("title", weight=5.0), TextField("body"), TagField("url", sortable=True) ] definition = IndexDefinition(prefix=["doc:"]) # Create Index idx = SearchIndex(client, "myIndex") idx.create_index(fields=schema, definition=definition) # Adding a document client.hset("doc:1", mapping={ "title": "Redisearch Introduction", "body": "Learn how to use Redisearch for full-text search capabilities", "url": "https://example.com/docs/redisearch" }) # Perform a search res = idx.search("Redisearch") for doc in res.docs: print(f"Document {doc.id}: {doc.title}")
Hash: 87447e5786e8022d2852713336b16a145918c906928001e4c920f80b7d930a47