Class: Leann::Rails::Searcher

Inherits:
Object
  • Object
show all
Defined in:
lib/leann/rails/searcher.rb

Overview

Handles search operations on a database-stored index

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(index) ⇒ Searcher

Returns a new instance of Searcher.

Parameters:



11
12
13
14
# File 'lib/leann/rails/searcher.rb', line 11

def initialize(index)
  @index = index
  @embedding_provider = nil
end

Instance Attribute Details

#indexLeann::Rails::Index (readonly)

Returns:



8
9
10
# File 'lib/leann/rails/searcher.rb', line 8

def index
  @index
end

Instance Method Details

#search(query, limit: 5, threshold: nil, filters: nil) ⇒ Leann::SearchResults

Search the index

Parameters:

  • query (String)

    Search query

  • limit (Integer) (defaults to: 5)

    Maximum results

  • threshold (Float, nil) (defaults to: nil)

    Minimum score threshold

  • filters (Hash, nil) (defaults to: nil)

    Metadata filters

Returns:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/leann/rails/searcher.rb', line 23

def search(query, limit: 5, threshold: nil, filters: nil)
  start_time = Time.now

  # Compute query embedding
  query_embedding = embedding_provider.compute([query]).first

  # Load all passages for embedding recomputation
  passages = load_all_passages

  # Search with on-the-fly embedding recomputation
  backend = ActiveRecordBackend.new(index)
  raw_results = backend.search(
    query_embedding,
    embedding_provider: embedding_provider,
    passages: passages,
    limit: limit * 2
  )

  # Build results
  results = raw_results.map do |id, score|
    passage = index.passages.find_by(external_id: id)
    next unless passage

    Leann::SearchResult.new(
      id: id,
      text: passage.text,
      score: score,
      metadata: passage.
    )
  end.compact

  # Apply threshold filter
  results = results.select { |r| r.score >= threshold } if threshold

  # Apply metadata filters
  results = apply_filters(results, filters) if filters

  # Limit and sort results
  results = results.sort.first(limit)

  duration = Time.now - start_time

  Leann::SearchResults.new(results, query: query, duration: duration)
end