123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::SearchIndexable

Relationships & Source Files
Namespace Children
Modules:
Classes:
Extension / Inclusion / Inheritance Descendants
Included In:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ActiveSupport::Concern
Defined in: lib/mongoid/search_indexable.rb

Overview

Encapsulates behavior around managing search indexes. This feature is only supported when connected to an Atlas cluster.

Instance Method Summary

DSL Calls

included

[ GitHub ]


53
54
55
56
# File 'lib/mongoid/search_indexable.rb', line 53

included do
  cattr_accessor :search_index_specs
  self.search_index_specs = []
end

Instance Method Details

#vector_search(index: nil, path: nil, limit: 10, num_candidates: nil, filter: nil, pipeline: []) ⇒ Array<Mongoid::Document>

Performs a vector search for documents similar to this one, using this document’s stored embedding as the query vector. The document itself is excluded from the results.

Examples:

Find articles similar to this one.

article.vector_search(limit: 5, filter: { status: 'published' })

Parameters:

  • index (String | Symbol | nil)

    The name of the vector search index to use (optional if only one is declared on the model).

  • path (String | Symbol | nil)

    The field containing the stored vector (optional if unambiguous from the index definition).

  • limit (Integer)

    The maximum number of results (default: 10).

  • num_candidates (Integer | nil)

    The number of candidates to consider during the ANN search; defaults to limit * 10.

  • filter (Hash | nil)

    An optional MongoDB filter to pre-filter candidates before scoring.

  • pipeline (Array)

    Additional aggregation stages to append after the vector search and score projection.

Returns:

[ GitHub ]

  
# File 'lib/mongoid/search_indexable.rb', line 79

def vector_search(index: nil, path: nil, limit: 10, num_candidates: nil, filter: nil, pipeline: [])
  _index, resolved_path = self.class.send(:resolve_vector_index, index, path)
  query_vector = public_send(resolved_path)

  if query_vector.nil?
    raise ArgumentError,
          "#{resolved_path} is nil on this document; cannot perform vector search"
  end

  self_filter = { '_id' => { '$ne' => _id } }
  combined_filter = filter ? { '$and' => [ self_filter, filter ] } : self_filter

  self.class.vector_search(
    query_vector,
    index: index,
    path: path,
    limit: limit,
    num_candidates: num_candidates,
    filter: combined_filter,
    pipeline: pipeline
  )
end