Module: Zvec::ActiveRecord::Vectorize::SearchMethods
- Defined in:
- lib/zvec/active_record.rb
Overview
Class methods mixed into the model.
Instance Method Summary collapse
-
#vector_search(query, top_k: 10, embed: true) ⇒ Array<ActiveRecord::Base>
Search for records by vector similarity.
-
#zvec_store ⇒ Zvec::RubyLLM::Store
Access the shared RubyLLM::Store instance for this model.
Instance Method Details
#vector_search(query, top_k: 10, embed: true) ⇒ Array<ActiveRecord::Base>
Search for records by vector similarity.
When query is a String and embed is true, the configured
embed_with function is called to convert it to a vector first.
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
# File 'lib/zvec/active_record.rb', line 135 def vector_search(query, top_k: 10, embed: true) cfg = zvec_config query_vector = if && query.is_a?(String) && cfg[:embed_with] cfg[:embed_with].call(query) elsif query.is_a?(Array) query else raise ArgumentError, "query must be a vector Array or a String with embed_with configured" end results = zvec_store.search(query_vector, top_k: top_k) ids = results.map { |r| r[:id] } records = where(id: ids).index_by { |r| r.id.to_s } results.filter_map do |r| record = records[r[:id]] next unless record record.define_singleton_method(:zvec_score) { r[:score] } record end end |
#zvec_store ⇒ Zvec::RubyLLM::Store
Access the shared RubyLLM::Store instance for this model.
112 113 114 115 116 117 118 119 120 121 |
# File 'lib/zvec/active_record.rb', line 112 def zvec_store @zvec_store ||= begin cfg = zvec_config Zvec::RubyLLM::Store.new( cfg[:zvec_path], dimension: cfg[:dimensions], metric: cfg[:metric] ) end end |