Valkey: Example: Using Valkey search in Python

This documentation is part of the Search and JSON guide. You can view the complete guide here: Store and query JSON documents with the Valkey search module.

👋 Welcome to the Stackhero documentation!

Stackhero provides a ready-to-use Valkey cloud solution offering numerous advantages, including:

  • Redis Commander web interface included.
  • Unlimited message size and transfers.
  • One-click simplified updates.
  • Optimal performance and enhanced security thanks to a private, dedicated infrastructure.

Save time and make your life easier: it only takes 5 minutes to try Stackhero's Valkey cloud hosting solution!

You can use the redis-py client to make use of Valkey's search features:

import os
import redis
from redis.commands.search.field import TextField, TagField, NumericField
from redis.commands.search.index_definition import IndexDefinition, IndexType
from redis.commands.search.query import Query

r = redis.from_url(os.environ['STACKHERO_VALKEY_URL_TLS'], decode_responses=True)

# Create the index once at startup
try:
    r.ft('productsIndex').create_index(
        (TextField('name'), TagField('brand'), NumericField('price')),
        definition=IndexDefinition(prefix=['product:'], index_type=IndexType.HASH),
    )
except redis.ResponseError as error:
    if 'Index already exists' not in str(error):
        raise

r.hset('product:1', mapping={'name': 'Espresso machine', 'brand': 'Bianca', 'price': 459})

results = r.ft('productsIndex').search(Query('@brand:{Bianca} @price:[0 500]'))
print(results.total, results.docs)