liveBook · Manning

Chapter 10: Query generation, routing, and retrieval postprocessing

What you will learn in chapter 10 of AI Agents and Applications

The introduction connects earlier RAG accuracy improvements to the chapter’s upcoming work on query generation, routing, and retrieval postprocessing.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction connects earlier RAG accuracy improvements to the chapter’s upcoming work on query generation, routing, and retrieval postprocessing.

Key terms: Retrieval-Augmented Generation (RAG), advanced indexing, query transformations, vector store retrieval

10.1 Content database query generation

The section surveys how LLM applications retrieve information from different content databases and how LLMs can bridge natural-language questions and database-specific queries.

Key terms: unstructured user questions, structured queries, content stores, dense retrieval, sparse retrieval, lexical retrieval, embeddings, inverted index, BM25, relational (SQL) database

10.2 Self-querying (metadata query enrichment)

This section explains how metadata attached to document chunks lets a vector store combine semantic search with keyword-based filtering, and how self-querying derives those filters from a user’s question.

Key terms: document chunks, embedding, dense search, metadata tags, keyword-based indexing, TF-IDF, self-querying, self-metadata querying, metadata filter, semantic component

10.2.1 Ingestion: Metadata enrichment

This section prepares a ChromaDB collection of UK tourist destination chunks with metadata so later queries can filter search results.

Key terms: metadata, document chunk, ChromaDB collection, metadata filters, source, destination, region

10.2.2 Q&A on a metadata-enriched collection

This section shows three ways to filter retrieval from a metadata-enriched vector collection: manually, with SelfQueryRetriever, or through a structured LLM-generated query.

Key terms: explicit metadata filter, retriever, destination, SelfQueryRetriever, metadata attributes, filter criteria, structured LLM function call, DestinationSearch, content_search, ChromaDB filter

10.3 Generating a structured SQL query

The section introduces LLM-generated SQL and explains how schema-grounded prompts can reduce incorrect table and column references.

Key terms: text-to-SQL, few-shot prompts, schema, sample records, CREATE TABLE, hallucinations

10.3.1 Installing SQLite

This section gives the minimal steps for making SQLite available from the command line.

Key terms: SQLite, Path environment variable

10.3.2 Setting up and connecting to the database

This section sets up the UkBooking SQLite database, explains its relational diagram, and verifies that LangChain can connect to it.

Key terms: UkBooking, SQLite terminal, SQL scripts, Offer table, Jupyter Notebook, LangChain, relational diagram, primary key (PK), foreign key (FK), destinations

10.3.3 Generating SQL queries from natural language

This section shows how to generate SQL from a natural-language question and clean its formatting before execution.

Key terms: natural language questions, generated SQL query, backticks, LLM, chain

10.3.4 Executing the SQL query

This section explains how a combined chain retrieves relational data by generating and executing SQL, and notes a LangChain alternative for generating queries.

Key terms: sql_query_gen_and_exec_chain, relational database, RAG, SQLDatabaseChain, LLM, database connection, few-shot prompts

10.4 Generating a semantic SQL query

The section contrasts exact-match SQL queries with semantic SQL search, which aims to find results similar in meaning to a user’s intent.

Key terms: strict SQL, exact matching, semantic SQL search

10.4.1 Standard SQL query

This section contrasts exact-match SQL filtering with LIKE-based partial matching and shows that both can miss name variations.

Key terms: standard SQL query, exact matches, LIKE operator, partial matching

10.4.2 Semantic SQL query

Introduces semantic SQL search as embedding-based similarity search in relational databases, contrasting it with exact text matching.

Key terms: semantic SQL search, SQL similarity search, embeddings, vector-based similarity searches

10.4.3 Creating the embeddings

This section explains how to prepare PostgreSQL fields for pgvector similarity search by storing embeddings alongside the values being searched.

Key terms: pgvector, VECTOR, embeddings, similarity search, OpenAIEmbeddings

10.4.4 Performing a semantic SQL search

The section shows that a semantic SQL search can return name variations by ordering results according to similarity.

Key terms: embeddings, similarity search, indexing, similarity

10.4.5 Automating semantic SQL search

This section previews using a prompt and an LCEL chain to automate semantic SQL searches and pass results to an LLM.

10.4.6 Benefits of a semantic SQL search

Semantic SQL supports nuanced searches by combining semantic filters with exact SQL matching, including across joined tables.

Key terms: semantic filtering, exact matching, multiple semantic filters, joins, traditional SQL filtering

10.5 Generating queries for a graph database

The section explains how graph databases represent relationships and how LLMs can help turn natural-language questions into graph queries and answers.

Key terms: graph database, nodes, edges, knowledge graph, RDF, triples, subject-predicate-object, SPARQL, Cypher, Gremlin

10.6 Chain routing

Explains why a RAG application may need task-specific branches and how a routing chain selects one for a user question.

Key terms: RAG architecture, routing chain, vector store, UkBooking database

10.6.1 Setting up data retrievers

This subsection sets up retriever chains for an existing vector store and relational database so questions can be sent to the appropriate data source.

Key terms: vector store, relational database, retriever chains

10.6.2 Setting up the query router

This section sets up an LLM-based router that chooses a data source from a question’s intent, then uses that choice to select a retriever chain.

Key terms: question router, datasource, tourist_info_store, uk_booking_db, retriever chooser, retriever chain, data source

10.6.3 Integrating the chain router into a full RAG chain

This section shows how a chain router fits into a RAG chain that selects a retriever, retrieves context, and generates an answer.

Key terms: chain router, RAG chain, retriever, context, original question, LLM

10.7 Retrieval postprocessing

This section introduces retrieval postprocessing as a way to filter retrieved document chunks before an LLM uses them to generate an answer.

Key terms: retrieval postprocessing, document chunks, answer synthesis

10.7.1 Similarity postprocessors

This section explains how a similarity-score cutoff filters retrieved chunks before they reach the LLM.

Key terms: similarity retriever, similarity score, similarity_score_threshold, search_kwargs, get_relevant_documents()

10.7.2 Keyword postprocessors

This section introduces keyword-based filtering of retrieved document chunks as a postprocessing step.

Key terms: keyword postprocessor, required_keywords, excluded_keywords, retrieved document chunks

10.7.3 Time weighting

This section explains how retrieval can favor chunks that are both relevant and recently accessed.

Key terms: last_accessed_at, TimeWeightedVectorStoreRetriever, time decay factor, similarity score, recency

10.7.4 RAG fusion (Reciprocal Rank Fusion)

This section explains how RAG fusion uses multiple queries and Reciprocal Rank Fusion to rerank retrieved documents before answer synthesis.

Key terms: multiple alternative queries, RAG fusion, Reciprocal Rank Fusion, RRF score, rank, k, RAG fusion retrieval chain

10.8 Summary

The section summarizes how RAG systems query different data stores, route questions to suitable sources, and combine keyword and semantic retrieval results.

Where this is used later

Concepts explained in this chapter

← Chapter 9: Question transformations Chapter 11: Building tool-based agents with LangGraph →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.