From b3ac13de7ed1c6b7acbf32381399186fe1edfe56 Mon Sep 17 00:00:00 2001 From: Thaddeus Jiang Date: Tue, 22 Oct 2024 19:21:21 +0900 Subject: [PATCH] fix: filter_by => belongs_to_id:123 (#19) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: filter_by => belongs_to_id:123 * style: 💄 clean code --- lib/save_it/bot.ex | 5 +++-- lib/save_it/typesense_photo.ex | 11 +++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/save_it/bot.ex b/lib/save_it/bot.ex index 319a8af..9d8fa48 100644 --- a/lib/save_it/bot.ex +++ b/lib/save_it/bot.ex @@ -114,7 +114,7 @@ defmodule SaveIt.Bot do end def handle({:command, :search, %{chat: chat, photo: nil, text: q}}, _context) do - photos = TypesensePhoto.search_photos!(q: q) + photos = TypesensePhoto.search_photos!(q: q, belongs_to_id: chat.id) answer_photos(chat.id, photos) end @@ -266,7 +266,8 @@ defmodule SaveIt.Bot do if typesense_photo != nil do TypesensePhoto.search_photos!( typesense_photo["id"], - distance_threshold: distance_threshold + distance_threshold: distance_threshold, + belongs_to_id: chat_id ) end end diff --git a/lib/save_it/typesense_photo.ex b/lib/save_it/typesense_photo.ex index 9bcf152..34b2744 100644 --- a/lib/save_it/typesense_photo.ex +++ b/lib/save_it/typesense_photo.ex @@ -25,7 +25,7 @@ defmodule SaveIt.TypesensePhoto do Typesense.get_document("photos", photo_id) end - def search_photos!(q: q) do + def search_photos!(q: q, belongs_to_id: belongs_to_id) do req_body = %{ "searches" => [ %{ @@ -34,6 +34,7 @@ defmodule SaveIt.TypesensePhoto do "collection" => "photos", "prefix" => false, "vector_query" => "image_embedding:([], k: 5, distance_threshold: 0.75)", + "filter_by" => "belongs_to_id:#{belongs_to_id}", "exclude_fields" => "image_embedding" } ] @@ -46,12 +47,17 @@ defmodule SaveIt.TypesensePhoto do end def search_photos!(id, opts \\ []) do + belongs_to_id = Keyword.get(opts, :belongs_to_id) distance_threshold = Keyword.get(opts, :distance_threshold, 0.4) - search_similar_photos!(id, distance_threshold: distance_threshold) + search_similar_photos!(id, + distance_threshold: distance_threshold, + belongs_to_id: belongs_to_id + ) end def search_similar_photos!(photo_id, opts \\ []) when is_binary(photo_id) do + belongs_to_id = Keyword.get(opts, :belongs_to_id) distance_threshold = Keyword.get(opts, :distance_threshold, 0.4) req_body = %{ @@ -61,6 +67,7 @@ defmodule SaveIt.TypesensePhoto do "q" => "*", "vector_query" => "image_embedding:([], id:#{photo_id}, distance_threshold: #{distance_threshold}, k: 4)", + "filter_by" => "belongs_to_id:#{belongs_to_id}", "exclude_fields" => "image_embedding" } ]