0Pricing
LangChain / RAG / Vector DBs · บทเรียน

การค้นหาแบบผสมและการจัดอันดับใหม่

ผสานการค้นหาด้วยคำสำคัญและการค้นหาเชิงความหมายเข้าด้วยกัน และใช้โมเดลจัดอันดับใหม่เพื่อจัดลำดับเอกสารที่เกี่ยวข้องที่สุด

การค้นหาแบบผสมและการจัดอันดับใหม่ เป็นบทเรียน LangChain / RAG / Vector DBs ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน LangChain / RAG / Vector DBs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Beyond Basic Retrieval

When building advanced Retrieval Augmented Generation (RAG) systems, simply finding documents isn't enough. We need to find the most relevant documents efficiently.

Traditional keyword or semantic searches, while powerful, each have limitations. To overcome these, we can combine their strengths.

Keyword Search: Specificity

Keyword search (also known as sparse retrieval, e.g., using BM25 or TF-IDF) is excellent for finding exact matches and specific terms.

  • Strengths: Great for precise queries, proper nouns, and when you know the exact wording.
  • Weaknesses: Struggles with synonyms, different phrasing, or understanding conceptual meaning.

For example, searching 'Python list append' works well, but 'add element to Python array' might miss results.

Semantic Search: Understanding Meaning

Semantic search (dense retrieval, using embeddings) understands the meaning and context of your query and documents.

  • Strengths: Handles synonyms, rephrased questions, and conceptual searches effectively.
  • Weaknesses: Can struggle with very specific, rare terms or highly technical jargon if not well-represented in its embedding space.

It can understand 'add element to Python array' is similar to 'Python list append'.

Introducing Hybrid Search

Hybrid search combines the best of both worlds: the precision of keyword search and the contextual understanding of semantic search.

By running both types of retrieval and intelligently merging their results, hybrid search can significantly improve the relevance and completeness of retrieved documents for your RAG system.

Merging Results: Reciprocal Rank Fusion

A common method to combine results from multiple retrievers in hybrid search is Reciprocal Rank Fusion (RRF).

RRF assigns a score to each document based on its rank in each individual retriever's result list. Documents that appear high in multiple lists get a boosted score, leading to a more robust final ranking.

Try running this simplified example of RRF:

def reciprocal_rank_fusion(rank_lists, k=60):
    fused_scores = {}
    for rank_list in rank_lists:
        for rank, doc_id in enumerate(rank_list):
            if doc_id not in fused_scores:
                fused_scores[doc_id] = 0.0
            fused_scores[doc_id] += 1.0 / (k + rank + 1)
    
    sorted_docs = sorted(fused_scores.items(), key=lambda item: item[1], reverse=True)
    return [doc_id for doc_id, score in sorted_docs]

if __name__ == "__main__":
    # Simulate results from two retrievers
    keyword_results = ["docA", "docC", "docB", "docE"]
    semantic_results = ["docB", "docA", "docD", "docC"]

    fused_order = reciprocal_rank_fusion([keyword_results, semantic_results])
    print("Fused Order:", fused_order)

Hybrid Search with LangChain

LangChain provides an EnsembleRetriever to easily implement hybrid search. It takes multiple retrievers (e.g., a keyword retriever and a vector store retriever) and combines their results, often using RRF by default.

This allows you to leverage both precise keyword matches and semantic understanding in one powerful retrieval step.

# from langchain.retrievers import EnsembleRetriever
# from langchain_community.retrievers import BM25Retriever
# from langchain_community.vectorstores import FAISS
# from langchain_openai import OpenAIEmbeddings

# # Assume you have a BM25 retriever and a vector store retriever
# bm25_retriever = BM25Retriever.from_documents(docs)
# vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
# vectorstore_retriever = vectorstore.as_retriever()

# ensemble_retriever = EnsembleRetriever(retrievers=[
#     bm25_retriever, 
#     vectorstore_retriever
# ], weights=[0.5, 0.5])

# # query = "What are the capital cities of Europe?"
# # docs = ensemble_retriever.invoke(query)

The Need for Re-ranking

Even after hybrid search, the initial set of retrieved documents might contain some noise or documents that are not perfectly ordered by relevance.

Re-ranking is a crucial next step. It takes the top-k documents from the initial retrieval and re-evaluates their relevance to the query using a more sophisticated model.

How Re-ranking Works

A re-ranking model, often a cross-encoder, takes both the user query and each retrieved document as input.

Unlike embedding models that create separate embeddings, a cross-encoder jointly processes the query and document to generate a single relevance score. This allows for a more nuanced understanding of their interaction.

Integrating Re-rankers

Various re-ranking models and services are available, such as Cohere's Re-rank API or open-source cross-encoders from libraries like sentence-transformers.

Integrating a re-ranker typically involves passing the initial retrieval results and the query to the re-ranker, which then returns the documents in a new, optimized order.

# from langchain.retrievers.document_compressors import CohereRerank
# from langchain.retrievers import ContextualCompressionRetriever

# # Assume you have an existing base_retriever (e.g., your EnsembleRetriever)
# # base_retriever = ensemble_retriever

# # Initialize the Cohere Rerank compressor
# # cohere_re_ranker = CohereRerank(top_n=5, cohere_api_key="YOUR_COHERE_API_KEY")

# # Create a compression retriever that uses the re-ranker
# # compression_retriever = ContextualCompressionRetriever(
# #     base_compressor=cohere_re_ranker,
# #     base_retriever=base_retriever
# # )

# # query = "What is the capital of France?"
# # compressed_docs = compression_retriever.invoke(query)

The Full Advanced Retrieval Pipeline

By combining hybrid search and re-ranking, you create a robust retrieval pipeline:

  1. User Query
  2. Hybrid Search: Combines keyword and semantic retrieval to get an initial set of relevant documents.
  3. Re-ranking: A specialized model re-orders the top documents from hybrid search for maximum relevance.
  4. Context for LLM: The highly relevant, re-ranked documents are passed to the LLM for generation.

This approach leads to more accurate and contextually rich answers from your RAG system.

Quick Check: Retrieval Steps

Which of the following statements accurately describe the roles of Hybrid Search and Re-ranking in a RAG system?

Recap: Advanced Retrieval

We've explored advanced retrieval techniques to boost RAG performance:

  • Hybrid Search: Combines keyword and semantic approaches for comprehensive initial retrieval.
  • Reciprocal Rank Fusion (RRF): A method to merge and score results from different retrievers.
  • Re-ranking: Uses specialized models (like cross-encoders) to refine the relevance order of retrieved documents.

These techniques ensure your RAG system provides the most accurate and contextually relevant information to the LLM.

คำถามที่พบบ่อย

บทเรียน “การค้นหาแบบผสมและการจัดอันดับใหม่” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การค้นหาแบบผสมและการจัดอันดับใหม่” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส LangChain / RAG / Vector DBs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การค้นหาแบบผสมและการจัดอันดับใหม่”

ผสานการค้นหาด้วยคำสำคัญและการค้นหาเชิงความหมายเข้าด้วยกัน และใช้โมเดลจัดอันดับใหม่เพื่อจัดลำดับเอกสารที่เกี่ยวข้องที่สุด คุณปฏิบัติ LangChain / RAG / Vector DBs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน LangChain / RAG / Vector DBs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน LangChain / RAG / Vector DBs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การค้นหาแบบผสมและการจัดอันดับใหม่” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน LangChain / RAG / Vector DBs นี้ได้ไหม

ได้ บทเรียน LangChain / RAG / Vector DBs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. กลยุทธ์การเรียกคืนจากหลายคำค้น
  2. การบีบอัดบริบทด้วย LLM
  3. การค้นหาแบบผสมและการจัดอันดับใหม่
  4. การค้นคืนเอกสารแม่และหน้าต่างประโยค
← กลับไปที่ LangChain / RAG / Vector DBs