Repository navigation
Vector and Hybrid search
This recipe changes a stock Blacklight 9 install so it can run vector (semantic) search against Solr dense vector fields. A second part adds hybrid search, which combines keyword and vector results. It follows the approach used in sul-dlss-labs/semantic-search (see search_builder.rb).
Blacklight needs no patches for any of this. The work is done by:
- Solr's dense vector field and its
vectorSimilarity/knnquery parsers - a custom
SearchBuilderprocessor that embeds the user's query and writes a JSON Query DSL query - for RRF hybrid search only, a small
Repositorysubclass that sends the request to a different Solr handler
What you need:
- Blacklight 9 (tested on 9.2; any version that sends
jsonparams as a JSON Query DSL request should work) - Solr 9.x for vector search and score-blended hybrid search, and Solr 10.1+ for RRF hybrid search
- an embedding model you can call at query time. It must be the same model that produced the document vectors.
The dimension must match your embedding model's output. We use 768 dimensions with cosine similarity:
<fieldType name="knn_vector_768" class="solr.DenseVectorField"
vectorDimension="768" similarityFunction="cosine" />
<field name="vector" type="knn_vector_768" indexed="true" stored="true" />Every document you want to find semantically needs a vector value: an array of floats from your embedding model, computed from whatever text represents the record (title, abstract, full text, and so on). Indexing happens outside Blacklight. We use a Python pipeline (sdr-harvest), but any indexer can do it:
{ "id": "abc123", "title_tesim": ["..."], "vector": [0.0123, -0.0456, ...] }Tip: Many embedding models are asymmetric. Queries and documents are embedded differently, for example by prefixing queries with a task instruction. Check your model's documentation and use the query form at search time.
Any HTTP client will work. This example calls an OpenAI-compatible /embeddings endpoint (we use a LiteLLM proxy in front of Gemini Embedding 2) and caches the result, because the same query is often embedded several times (paging, facet clicks, and so on):
# app/models/query_embedding.rb
require "net/http"
class QueryEmbedding
MODEL = "gemini-embedding-2"
DIMENSIONS = 768
def self.for(query)
Rails.cache.fetch("embedding/#{query}") { new.embed(query) }
end
def embed(text)
uri = URI("#{ENV.fetch('EMBEDDING_API_BASE')}/v1/embeddings")
response = Net::HTTP.post(
uri,
{ model: MODEL, input: [text], dimensions: DIMENSIONS }.to_json,
"Authorization" => "Bearer #{ENV.fetch('EMBEDDING_API_KEY')}",
"Content-Type" => "application/json"
)
raise "Embedding request failed (#{response.code})" unless response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body).dig("data", 0, "embedding")
end
endWhen the user asks for a vector search, replace the keyword query with a vectorSimilarity query. If Blacklight finds a json key in the Solr parameters, it POSTs a JSON Query DSL request and puts all the other parameters (fq, facets, rows, sort, …) in its params block. Facets, filters, paging and sorting therefore keep working.
# app/models/search_builder.rb
class SearchBuilder < Blacklight::SearchBuilder
include Blacklight::Solr::SearchBuilderBehavior
# Cosine similarity is normalized to [0, 1]. Matches scoring below this are dropped.
VECTOR_MIN_RETURN = 0.8
self.default_processor_chain += [:add_vector_query]
def add_vector_query(solr_parameters)
return unless search_state.params[:search_type] == "vector"
return if search_state.params[:q].blank?
# The JSON query replaces q. Leaving q in place makes Solr use it instead.
solr_parameters.delete(:q)
solr_parameters[:json] ||= {}
solr_parameters[:json][:query] = vector_query
end
private
def vector_query
{
vectorSimilarity: {
f: "vector",
minReturn: VECTOR_MIN_RETURN,
query: "[#{QueryEmbedding.for(search_state.params[:q]).join(', ')}]"
}
}
end
endvectorSimilarity or knn? We started with knn ({ knn: { f: "vector", topK: 100, query: ... } }) and switched to vectorSimilarity. knn always returns the topK nearest neighbours, however poor the matches are, so the result count barely depends on the query. vectorSimilarity returns everything above a similarity threshold, which gives you a useful hit count and keeps weak matches out of facet counts. Tune minReturn against real queries, because the right value depends on the model. Our relevant results scored as low as 0.84, so we used 0.8.
Allow the new parameter in the search state, so Blacklight keeps it in facet, paging and sort links:
# app/controllers/catalog_controller.rb
configure_blacklight do |config|
config.search_state_fields += [:search_type]
# Embedding vectors make long request bodies, so POST them to Solr.
config.http_method = :post
endThen submit search_type=vector from the search form, using a hidden field, a select, or a toggle. You can also choose the mode automatically: we use a small heuristic classifier (CatalogSearchClassifier) in a before_action. It sends quoted phrases, identifiers and title-like queries to keyword search, natural-language questions to vector search, and everything else to hybrid search.
Alternative: you could register
config.add_search_field "semantic"and checksearch_state.params[:search_field]in the processor. Blacklight would then show it in the search field dropdown with no extra form code.
A single vector can't represent a long document (a book or a thesis) well. We index each record as a Solr nested document: a parent holds the metadata, and each child holds one text chunk (about 1,200 characters) with its own vector. The parents are marked doc_type_ssi:parent. Wrap the vector query in a block-join parent query, so chunk matches roll up to their parent record and the parent takes the score of its best chunk:
def vector_query
{
parent: {
which: "doc_type_ssi:parent",
score: "max", # default is "none", which scores every match 0
query: {
vectorSimilarity: {
f: "vector",
minReturn: VECTOR_MIN_RETURN, # applied per chunk, before the roll-up
query: "[#{QueryEmbedding.for(search_state.params[:q]).join(', ')}]"
}
}
}
}
endDo the same for keyword search over chunk text: an edismax query on chunk_text_tesi inside the same parent wrapper. A phrase that appears in one chunk of a 1,000-page volume then isn't diluted by the length of the document.
Keyword search is precise for names, titles and identifiers. Vector search handles paraphrase and natural-language questions. Hybrid search runs both and merges the results. We've used two approaches.
Put the keyword query and a boosted vector query together as should clauses of a bool query. A document's score is the sum of its scores from each clause. This needs only the /select handler.
def add_hybrid_query(solr_parameters)
return unless search_state.params[:search_type] == "hybrid"
return if search_state.params[:q].blank?
keyword = { edismax: { query: solr_parameters.delete(:q) } }
vector = { boost: { b: 100.0, query: vector_query } }
solr_parameters[:json] ||= {}
solr_parameters[:json][:query] = { bool: { should: [keyword, vector] } }
endThe weakness is that BM25 scores have no upper bound, while cosine similarity runs from 0 to 1. The boost (b) puts them on a comparable scale, but the right value depends on the corpus and has to be tuned. A rerank stage can help: rescore the top N lexical-plus-vector hits with the vector query alone, using rq={!rerank reRankQuery=$rqq reRankDocs=100 reRankWeight=100} (see add_vector_rerank in our search_builder.rb).
RRF ignores raw scores and merges the two result lists by rank, so no boost needs tuning. Solr 10.1 added a CombinedQuerySearchHandler that runs several named queries and fuses them.
1. Add the handler to solrconfig.xml:
<requestHandler name="/hybrid" class="solr.CombinedQuerySearchHandler" />
<searchComponent name="combined_query" class="solr.CombinedQueryComponent" />2. Send combined queries to that handler. Blacklight sends JSON DSL requests to config.json_solr_path (or to solr_path). A small repository subclass sends only the combined queries to /hybrid:
# app/models/combined_query_repository.rb
class CombinedQueryRepository < Blacklight::Solr::Repository
private
def default_search_path(solr_params)
return "hybrid" if solr_params[:json]&.dig(:queries).present?
super
end
end# app/controllers/catalog_controller.rb
config.repository_class = CombinedQueryRepository3. Build the named queries in the SearchBuilder. Use json.queries instead of json.query, and set the combiner parameters:
def add_hybrid_query(solr_parameters)
return unless search_state.params[:search_type] == "hybrid"
return if search_state.params[:q].blank?
keyword = { edismax: { query: solr_parameters[:q] } }
# Each named query has its own parser. A request-level q confuses the combined handler.
solr_parameters.delete(:q)
solr_parameters[:json] = (solr_parameters[:json] || {}).except(:query).merge(
queries: { lexical: keyword, vector: vector_query }
)
solr_parameters[:combiner] = true
solr_parameters[:"combiner.query"] = %w[lexical vector]
solr_parameters[:"combiner.algorithm"] = "rrf"
endFilters (fq), facets and paging still go in the params block and apply to the fused result.
Notes:
-
combiner.queryis a list, so you can fuse more than two queries. With chunked documents, for example, ourlexicalquery is aboolof the metadata keyword query and the chunk keyword query, fused withvector. - Faceting multi-valued fields on
/hybridthrew an exception in early 10.1 release candidates. That was fixed in 10.1.0 RC2, so use 10.1.0 or later. - If Blacklight's advanced search is enabled, it builds
json.query.bool.mustitself. Move those clauses into yourlexicalquery rather than dropping them.
-
Verify in Solr first. Before wiring up Blacklight, POST the JSON a query should produce straight to
/selector/hybrid. Once that works,config.raw_endpointand the Solr request log help you compare it with what Blacklight sends. - Spellcheck and highlighting rely on lexical terms, so they do little in pure vector search. To show users why a document matched, we fetch the best-matching chunks in a separate request after the page renders.
-
Evaluate. Thresholds (
minReturn), boosts and classifier rules should come from a set of real queries with known relevant results, not from guesses.