Redis®*: Example: Using Python
This documentation is part of the Search and JSON guide. You can view the complete guide here: Store JSON documents and query them efficiently with the Redis query engine.
👋 Welcome to the Stackhero documentation!
Stackhero provides a ready-to-use Redis cloud solution offering numerous advantages, including:
- Redis Commander web interface included.
- Unlimited message size and transfers.
- Updates made easy with just one click.
- 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 Redis cloud hosting solution!
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_REDIS_URL_TLS'], decode_responses=True)
# Create the index at startup
try:
r.ft('productsIndex').create_index(
(
TextField('$.name', as_name='name'),
TagField('$.brand', as_name='brand'),
NumericField('$.price', as_name='price', sortable=True),
),
definition=IndexDefinition(prefix=['product:'], index_type=IndexType.JSON),
)
except redis.ResponseError as error:
if 'Index already exists' not in str(error):
raise
r.json().set('product:1', '$', {
'name': 'Espresso machine',
'brand': 'Bianca',
'price': 459,
})
results = r.ft('productsIndex').search(Query('@name:(espresso) @price:[0 500]'))
print(results.total, results.docs)