Valkey: 範例:在 Python 使用 Valkey 搜尋

本文件是搜尋與 JSON指南的一部分。請在此處查看完整指南:使用 Valkey 搜尋模組儲存與查詢 JSON 文件

👋 歡迎來到 Stackhero 文件中心!

Stackhero 提供即時可用的 Valkey cloud 解決方案,帶來多項優勢,包括:

  • 內建 Valkey Admin 網頁管理介面
  • 無限制的訊息大小與傳輸量。
  • 一鍵輕鬆完成更新
  • 專屬私有基礎架構提供最佳效能與強大安全性

節省時間簡化您的工作流程:只需 5 分鐘即可體驗 Stackhero 的 Valkey cloud hosting 解決方案!

您可以使用 redis-py client 操作 Valkey 搜尋功能:

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)

# 啟動時建立索引(僅需一次)
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)