Files
azfzagnetdoc/test_search.py
T

56 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
搜索测试:加载 local.settings.json,对 openclaw-resources 执行关键词搜索。
用法: python test_search.py [关键词]
"""
import json
import os
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SETTINGS_PATH = os.path.join(SCRIPT_DIR, "local.settings.json")
if os.path.exists(SETTINGS_PATH):
with open(SETTINGS_PATH, "r", encoding="utf-8") as f:
for k, v in json.load(f).get("Values", {}).items():
os.environ.setdefault(k, v)
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
from azure.search.documents.models import VectorizedQuery
ENDPOINT = os.environ.get("AZURE_SEARCH_ENDPOINT", "").rstrip("/")
API_KEY = os.environ.get("AZURE_SEARCH_API_KEY", "")
INDEX_NAME = os.environ.get("AZURE_SEARCH_INDEX_NAME", "openclaw-resources")
def main():
query = (sys.argv[1] if len(sys.argv) > 1 else "文档").strip()
if not ENDPOINT or not API_KEY:
print("错误: 请配置 AZURE_SEARCH_ENDPOINT 和 AZURE_SEARCH_API_KEY(或 local.settings.json)")
sys.exit(1)
client = SearchClient(
endpoint=ENDPOINT,
index_name=INDEX_NAME,
credential=AzureKeyCredential(API_KEY),
)
print(f"索引: {INDEX_NAME}")
print(f"关键词搜索: “{query}”\n")
# 1. 纯关键词搜索(不需 embedding)
results = client.search(search_text=query, top=5, select="id,title,content,source,updated_at")
hits = list(results)
print(f"结果数: {len(hits)}")
for i, r in enumerate(hits, 1):
title = (r.get("title") or "")[:60]
content_preview = (r.get("content") or "")[:120].replace("\n", " ")
print(f" {i}. [{r.get('id')}] {title}")
print(f" {content_preview}...")
print(f" score={r.get('@search.score')}")
if not hits:
print(" (无匹配结果;可先运行索引器或 upload_to_kb 写入数据)")
return 0
if __name__ == "__main__":
sys.exit(main())