Vector Databases: Pinecone, Weaviate & pgvector · 课时

语义搜索与混合搜索

实现结合向量相似度与关键词匹配的高级搜索技术,获得更优结果。

第 1 / 4 课11 个步骤

语义搜索与混合搜索 是 CoddyKit 上的免费 Vector Databases: Pinecone, Weaviate & pgvector 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Vector Databases: Pinecone, Weaviate & pgvector 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Beyond Basic Searches

Welcome! In this lesson, we'll dive into advanced search techniques in Weaviate. Moving past simple vector searches, we'll explore how to combine different methods for incredibly precise results.

We'll cover:

  • Pure semantic search
  • Traditional keyword (BM25) search
  • The power of hybrid search

Semantic Search: Meaning First

Semantic search finds items based on their meaning, not just exact words. It uses vector embeddings to represent data, measuring "distance" to find similar concepts. Weaviate uses .with_near_text() for this.

Try this example:

import weaviate
import os

# Connect to your Weaviate instance
# Ensure WEAVIATE_URL is set (e.g., "http://localhost:8080")
client = weaviate.Client(
    url=os.getenv("WEAVIATE_URL", "http://localhost:8080")
)

# Make sure you have an 'Article' class with 'title' and 'content' properties
# and some data imported for this to work!

query_concept = "latest advancements in technology"

response = client.query.get(
    "Article", # Your class name
    ["title", "content"]
).with_near_text(
    {"concepts": [query_concept]}
).with_limit(2).do()

print("Semantic Search Results:")
for item in response["data"]["Get"]["Article"]:
    print(f"- {item['title']}")

Keyword Search Fundamentals

While semantic search is powerful, sometimes you need to find exact keywords. This is where traditional keyword search comes in. Weaviate supports this using the BM25 algorithm.

BM25 (Best Match 25) is a ranking function used by search engines to estimate the relevance of documents to a given search query. It's great for precision when you know exactly what words you're looking for.

Keyword Search with BM25

You can perform keyword searches in Weaviate by combining a .with_where() filter with a text search, and asking for the _additional {score} to see BM25 relevance.

Here's how to search for articles containing specific keywords:

import weaviate
import os

# Connect to your Weaviate instance
client = weaviate.Client(
    url=os.getenv("WEAVIATE_URL", "http://localhost:8080")
)

# Make sure you have an 'Article' class with 'title' and 'content' properties
# and some data imported for this to work!

keyword_query = "AI" # Search for articles containing "AI"

response = client.query.get(
    "Article",
    ["title", "content", "_additional {score}"] # Request BM25 score
).with_where({
    "path": ["content"], # Search in the 'content' field
    "operator": "Like",
    "valueText": f"*{keyword_query}*" # Wildcard search
}).with_limit(2).do()

print("Keyword Search Results:")
for item in response["data"]["Get"]["Article"]:
    print(f"- {item['title']} (BM25 Score: {item['_additional']['score']:.2f})")

Why Hybrid? Limitations

Both semantic and keyword searches have strengths and weaknesses:

  • Semantic: Great for conceptual understanding, but can miss exact terms.
  • Keyword: Excellent for exact matches, but struggles with synonyms or nuanced meaning.

Imagine searching for "best car for family trips." Semantic search might show SUVs, while keyword search might only show articles with "family" and "trip." What if you want both?

Introducing Hybrid Search

Hybrid search combines the strengths of semantic (vector) search and keyword (BM25) search. It retrieves results based on both conceptual similarity and exact term matching, then intelligently fuses them.

This leads to more comprehensive and relevant results, especially for complex or ambiguous queries.

Weaviate's `with_hybrid`

Hybrid search combines semantic and keyword strengths. Weaviate's .with_hybrid() operator makes this easy. It takes both a query and an alpha parameter to control the blend:

  • alpha = 0: Pure keyword
  • alpha = 1: Pure semantic
  • alpha = 0.5: Equal blend (default)

Experiment with this:

import weaviate
import os

# Connect to your Weaviate instance
client = weaviate.Client(
    url=os.getenv("WEAVIATE_URL", "http://localhost:8080")
)

# Make sure you have an 'Article' class with 'title' and 'content' properties
# and some data imported for this to work!

query = "AI tools for data analysis" # Hybrid query text
alpha_value = 0.7 # 0.7 for more semantic weighting

response = client.query.get(
    "Article",
    ["title", "content", "_additional {score, id}"] # Request score & ID
).with_hybrid(
    query=query,
    alpha=alpha_value
).with_limit(3).do()

print(f"Hybrid Search Results (alpha={alpha_value}):")
for item in response["data"]["Get"]["Article"]:
    # The 'score' here is the hybrid score
    print(f"- {item['title']} (Score: {item['_additional']['score']:.2f})")

Understanding Result Fusion (RRF)

When you perform a hybrid search, Weaviate needs a way to combine the rankings from both the semantic and keyword searches into a single, unified list. This is often done using an algorithm like Reciprocal Rank Fusion (RRF).

RRF is a clever method that assigns a score to each document based on its rank in the individual search results. Documents that rank highly in both semantic and keyword searches will get a significantly boosted final score.

Benefits of Hybrid Search

Hybrid search offers several advantages:

  • Improved Relevance: Catches both exact matches and conceptually similar items.
  • Robustness: Performs well even with short, ambiguous, or rare queries.
  • User Satisfaction: Leads to more comprehensive and helpful search results.

It's a crucial technique for building advanced search experiences in AI applications.

Test Your Knowledge

Hybrid search combines semantic and keyword search. Which parameter in Weaviate's .with_hybrid() operator controls the balance between these two search types?

Summary of Advanced Search

Great job! You've mastered advanced search techniques in Weaviate. We explored:

  • Semantic Search: Based on meaning and vector similarity.
  • Keyword Search: Using BM25 for exact term matching.
  • Hybrid Search: Combining both for superior relevance, controlled by the alpha parameter.

These powerful tools will help you build more intelligent and robust search applications. Keep experimenting with different query types and alpha values!

免费开始

用 AI 导师学习 Vector Databases: Pinecone, Weaviate & pgvector — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「语义搜索与混合搜索」课时是免费的吗?

是的 — 「语义搜索与混合搜索」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Vector Databases: Pinecone, Weaviate & pgvector 课程的其余内容,请升级到 CoddyKit PRO。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。

「语义搜索与混合搜索」这节课中我会学到什么?

实现结合向量相似度与关键词匹配的高级搜索技术,获得更优结果。 你通过在浏览器中直接运行的动手代码来练习 Vector Databases: Pinecone, Weaviate & pgvector,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Vector Databases: Pinecone, Weaviate & pgvector 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Vector Databases: Pinecone, Weaviate & pgvector 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「语义搜索与混合搜索」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Vector Databases: Pinecone, Weaviate & pgvector 课中编写并运行代码吗?

能。每节 Vector Databases: Pinecone, Weaviate & pgvector 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 语义搜索与混合搜索
  2. 使用 Weaviate 模块
  3. 备份与恢复策略
  4. Weaviate 中的多租户
← 返回 Vector Databases: Pinecone, Weaviate & pgvector