Skip to content
Visual explainer 3h to learn 3 steps

Query rewriting, metadata filters & conversation memory

Handle follow-up questions and filter retrieval by user, date or type.

By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.

Topic 18 of 33

In short

Real conversations include follow-ups like what about the second one, which retrieve poorly on their own. Query rewriting, metadata filters and conversation memory make retrieval work across a whole chat.

Explained simply

Real users chat. They ask What does the Pro plan cost? and then And for teams? The second message makes sense to a person, but on its own it is a terrible search query. It has no subject, so search returns random chunks about teams.

Query rewriting fixes this. Before searching, a small model call turns the follow-up into a full standalone question, using the chat history: How much does the Team plan cost per month? That question finds the right chunks.

Metadata filters narrow the search to the right slice of documents: only this customer's files, only pricing pages, only documents from this year. Filters are also how you keep users from seeing documents they are not allowed to read.

Conversation memory is the history your app stores and sends back each turn, because the model itself remembers nothing between calls. Long chats need trimming or summarising, or they become slow and expensive.

Press Play on a diagram to walk through it one step at a time.

FlowHandling a follow-up question
  1. 1
    Follow-up arrives

    e.g. And for enterprise plans?

  2. 2
    Rewrite query

    LLM makes it standalone using chat history

  3. 3
    Apply filters

    User, date, document type or permissions

  4. 4
    Retrieve

    Search with the rewritten query

  5. 5
    Answer

    Use chunks plus summarised history

SequenceOne follow-up turn, start to finish
User
App
Small LLM
Vector store
  1. 1And for teams?
    User to App: And for teams?
  2. 2Load history for this chat
    App to App: Load history for this chat
  3. 3History plus message: rewrite
    App to Small LLM: History plus message: rewrite
  4. 4Team plan price per month
    Small LLM to App: Team plan price per month
  5. 5Search with tenant and type filters
    App to Vector store: Search with tenant and type filters
  6. 6Matching chunks
    Vector store to App: Matching chunks
  7. 7Answer from main model
    App to User: Answer from main model

In depth

Query rewriting and its cousins

The basic rewrite is one extra model call: give it the recent history and the new message, and ask for a standalone search query only. Use a small, fast model and a low temperature, and skip the call on the first turn, where there is no history to resolve.

There are related techniques for harder cases. Multi-query asks the model for three or four different phrasings, searches with each, and merges the results, which helps with vocabulary mismatch. Decomposition splits a question with several parts (compare plan A and plan B) into sub-questions that are searched separately. HyDE (hypothetical document embeddings) asks the model to write a fake answer first and searches with that, because an answer often looks more like the documents than a short question does.

Every extra call adds latency and cost, so measure whether it improves retrieval on your eval set before keeping it.

MapWays to transform a query before search
User message
  • Standalone rewrite
    • Resolves it and that
    • One cheap call
  • Multi-query
    • 3 to 4 phrasings
    • Merge the results
  • Decomposition
    • Split multi-part questions
    • Search each part
  • HyDE
    • Write a fake answer
    • Search with its embedding

Metadata filters: before or after the search?

A filter like doc_type = pricing can be applied in two places. Post-filtering takes the top k results and then throws away the ones that do not match. That is simple but dangerous: if all five top results are from other document types, you end up with nothing. Pre-filtering puts the condition inside the database query, so the k results all match.

With approximate indexes such as HNSW there is a subtlety. The index walks a graph of nearest neighbours and the filter is checked on the way, so a strict filter can still return fewer than k rows. pgvector 0.8 added iterative index scans (the hnsw.iterative_scan setting) that keep searching until enough matching rows are found. Another fix for very selective filters is a separate index or partition per tenant.

A model can also choose filters from the question (self-query): from 2025 billing docs becomes year = 2025 and type = billing. Validate those values like any untrusted input.

ComparePost-filter vs pre-filter
Post-filter
  • Search top k, then drop non-matches
  • Can leave zero results
  • Restricted text may already be loaded
Pre-filter
  • Filter inside the database query
  • All k results match
  • Restricted rows never leave the database

Permissions belong to the server, not the model

In a multi-user app, the most important filter is who may see what. Store access data on every chunk, such as tenant_id and a list of allowed groups. At query time, take the user's tenant and groups from the authenticated session on your server, and add them to the search query.

Never let the model decide security filters, and never read them from the request body. A prompt injection or a curious user could otherwise ask for another tenant's documents. The model may pick convenience filters like date or document type; the server always adds the security ones on top.

In Postgres, the array overlap operator makes group checks simple: allowed_groups && the user's groups. Row-level security policies can act as a second safety net, so even a bug in your query code cannot return another tenant's rows.

  • tenant_id comes from the session, never from the prompt
  • allowed_groups && ARRAY['sales','all'] checks group access
  • Filter before retrieval so restricted text never reaches the prompt

Conversation memory: window, summary and long-term facts

Chat APIs are stateless, so your app stores each conversation (for example in a table keyed by conversation_id) and sends history back every turn. Sending everything forever does not scale: cost and latency grow with each turn, and very long histories can push out room for retrieved chunks.

A common pattern is a sliding window plus a summary. Keep the last few turns word for word, because recent details matter most. Every few turns, ask a small model to fold older turns into a short running summary, and send that instead of the old messages.

Some apps also keep long-term memory: durable facts like the user prefers metric units, stored separately and retrieved when relevant, much like documents. Treat stored memory as user data: let people see and delete it, and avoid saving secrets.

LayersSplitting the context budget in a chat RAG app
  1. 1
    System prompt

    Rules and refusal phrase

  2. 2
    Summary of older turns

    A few hundred tokens

  3. 3
    Last few turns verbatim

    Recent details stay exact

  4. 4
    Retrieved chunks

    Usually the biggest share

  5. 5
    New question

    Always last

Learn it in 3 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Rewrite follow-up questions as standalone~1h
  2. 2
    Filter retrieval by metadata~1h
  3. 3
    Store and summarise conversation history~1h

Key points

  • Rewrite follow-ups into standalone questions before searching.
  • Filter by metadata in the database query, not after retrieval.
  • Permission filters ensure users only retrieve documents they may see.
  • Summarise old turns to keep history short and within budget.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
REWRITE_PROMPT = '''Rewrite the last user message as a standalone search query.
Use the chat history for missing details. Return only the query.

History:
{history}

Last message: {message}'''

# history: 'What does the Pro plan cost?' -> '$20 per month'
# message: 'And for enterprise?'
# rewritten: 'Enterprise plan price per month'

filters = {'doc_type': 'pricing', 'tenant_id': 'acme'}

A rewrite prompt and the filters applied at search time.

Rewriting a follow-up with a safe fallback

History: the user asked What does the Pro plan cost? and the bot said 20 dollars per month. Now the user writes And for teams? Step 1: if there is no history, search with the message as it is. Step 2: otherwise send the last few turns and the message to a small model with the rewrite prompt. Step 3: if the rewrite comes back empty or very long, fall back to the raw message rather than failing. Step 4: search with the rewritten query, but show the user's original words in the chat. Log both versions so you can debug bad rewrites later.

python
PROMPT = ("Rewrite the last message as a standalone search query. "
          "Use the history only to fill in missing details. Return only the query.\n\n"
          "History:\n{history}\n\nLast message: {message}")

def search_query(history: list[dict], message: str, small_llm) -> str:
    if not history:
        return message
    recent = "\n".join(f"{m['role']}: {m['content']}" for m in history[-6:])
    query = small_llm(PROMPT.format(history=recent, message=message)).strip()
    if not query or len(query) > 300:
        return message  # fall back instead of failing
    return query

A tenant-safe filtered vector search in pgvector

A SaaS app keeps every customer's documents in one chunks table. Step 1: read tenant_id and the user's groups from the verified session, never from the request body. Step 2: put both into the WHERE clause together with optional filters the user picked, like document type. Step 3: on pgvector 0.8 or newer, turn on iterative scans so a selective filter still returns up to k rows from the HNSW index. Step 4: order by cosine distance and limit to k.

sql
SET hnsw.iterative_scan = relaxed_order;  -- pgvector 0.8+

-- $1 query embedding, $2 tenant_id, $3 user's groups, $4 allowed doc types
SELECT id, source, content
FROM chunks
WHERE tenant_id = $2
  AND allowed_groups && $3
  AND doc_type = ANY($4)
  AND updated_at >= now() - interval '1 year'
ORDER BY embedding <=> $1
LIMIT 5;

Quick reference

  • Rewrite follow-ups into standalone queries; skip the rewrite on the first turn
  • Use a small fast model at low temperature for rewriting, and fall back to the raw message
  • Search with the rewritten query but show and store the user's original words
  • Pre-filter inside the database query; post-filtering can leave zero results
  • Security filters (tenant, groups) come from the session, never from the model or request
  • pgvector 0.8+: SET hnsw.iterative_scan = relaxed_order helps filtered HNSW queries return k rows
  • Memory pattern: last few turns verbatim plus a running summary of older ones

Common mistakes

  • Searching with the raw follow-up text, which lacks the subject.
  • Filtering out unauthorised documents only after they were sent to the model.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why does searching with the raw follow-up And for teams? usually fail?

Question 2

2You post-filter top 5 results by doc_type = pricing and get zero results. What is the better approach?

Question 3

3Where should the tenant_id used in the retrieval filter come from?

Question 4

4What does HyDE do?

Question 5

5A chat is 80 turns long and every request is slow and costly. What is a common fix?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write trim_history(history, keep) that returns only the last keep messages, but always keeps the very first user message (the original goal).

  2. Exercise 2medium

    Build a safe filter builder: it takes user-chosen filters (doc_type, year) and the session, validates doc_type against an allowed list, and always adds tenant_id from the session.

  3. Exercise 3hard

    Implement a memory class that keeps the last N messages verbatim and, when it grows past N, folds the oldest messages into a running summary using a summarise(old_summary, messages) function.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I always need query rewriting?
Only for conversational apps where follow-ups are common. For single-question search boxes it adds cost and latency without much gain.
Can I just send the whole chat history as the search query?
It usually works poorly. Long mixed text produces a blurry embedding; a short standalone rewrite matches documents much better.
How do I stop users seeing other customers' documents in RAG?
Store tenant and access data on each chunk and filter on it in the retrieval query using values from the authenticated session. Row-level security adds a second safety net.
What is the difference between conversation memory and RAG?
Memory is what was said in this chat; RAG retrieves facts from your document store. Many apps use both and give each a share of the context budget.
ShareXLinkedInWhatsApp