liveBook · Manning

Hybrid search

As explained in Generative AI in Action

Hybrid search combines multiple search methods, such as text-based, categorical, numerical, and vector-based retrieval, in one query.

Hybrid search combines multiple search types in one query. For example, an enterprise search application can combine text matching with vector search, or use numerical and categorical fields alongside vector retrieval. The appropriate combination depends on the data, requirements, and search engine. section 8.5 section 8.2

In Azure AI Search, full-text and vector queries run against an index containing searchable text and embeddings. Reciprocal rank fusion combines the matches into one result set. A request can also use filtering, faceting, sorting, scoring profiles, and semantic ranking. section 8.2

Searching blog posts with Redis

A console application turns a question into a vector and uses K-nearest neighbors to retrieve similar posts. Its hybrid_search function accepts search fields, requests the top three matches, and returns fields including title, content, and vector score. The default search fields are '*', so the shown default does not itself add a field restriction. section 8.5

Listing 8.8 Searching using Redis
def hybrid_search(query_vector, client, top_k=3, hybrid_fields="*"):
    base_query = f"{hybrid_fields}=>
                        [KNN {top_k} 
                        @embedding $vector AS vector_score]"  #1
    query = Query(base_query).return_fields(
        "url",                                               #2
        "title",                                            #2
        "publish_date",                                     #2
        "description",                                      #2
        "content",                                          #2
        "vector_score").sort_by("vector_score").dialect(2)   #3
    try:
        results = client.ft("posts").search(
            query, query_params={"vector": query_vector})  #4
    except Exception as e:
        print("Error calling Redis search: ", e)
        return None

    if results.total == 0:
        print("No results found for the given query vector.")
        return None

    return results

# Connect to the Redis server
conn = redis.Redis(...)

query = input("Enter your query: ")      #5

print("Vectorizing query...")
query_vector = get_embedding(query)    #6

query_vector = np.array(query_vector).astype(              #7

                        np.float32).tobytes()
print("Searching for similar posts...")
results = hybrid_search(query_vector, conn)                #8

if results:
    print(f"Found {results.total} results:")
    for i, post in enumerate(results.docs):
        score = 1 - float(post.vector_score)
        print(post.content)
else:
    print("No results found")

Inspect the Redis query construction, returned fields, vector parameter, and sorting. The listing is illustrative and includes basic error handling. section 8.5

In a retrieval-augmented chat application, the user's question is embedded and searched against indexed blog-post chunks. The retrieved chunks and original question are added to a prompt for the language model. The example retrieves five matches; it uses local Redis rather than a managed production search service. section 8.6 section 8.2

How Generative AI in Action covers it

How deep it goes
Explains query construction and result handling in Redis, and describes Azure's result fusion without mathematical derivation.
Examples
Uses a Longhorn blog-post query and an end-to-end chat application over indexed blog chunks.
What you can do after
Apply hybrid search via Redis to retrieve similar posts and supply results to a chat prompt.
How it connects
Connects vector embeddings and K-nearest neighbors with full-text search, reciprocal rank fusion, and retrieval-augmented generation.

Also explained in

Compare how 8 books explain hybrid search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Generative AI in Action. The section links point to the parts of the book it draws on.