Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for completion suggests #146

Merged
merged 2 commits into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/snap/responses/suggest/option.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,30 @@ defmodule Snap.Suggest.Option do
"""
defstruct ~w[
freq
id
index
score
source
text
]a

def new(response) do
%__MODULE__{
freq: response["freq"],
score: response["score"],
id: response["_id"],
index: response["_index"],
score: response["score"] || response["_score"],
source: response["_source"],
text: response["text"]
}
end

@type t :: %__MODULE__{
freq: integer(),
id: String.t() | nil,
index: String.t() | nil,
score: float(),
source: map() | nil,
text: String.t()
}
end
74 changes: 73 additions & 1 deletion test/search_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,80 @@ defmodule Snap.SearchTest do
assert first_hit.source["title"] == "Document 1"

assert %Snap.SearchResponse{
suggest: %{"title" => [%{text: "doument", options: [%{text: "document"}]}]}
suggest: %{
"title" => [
%Snap.Suggest{
text: "doument",
options: [%Snap.Suggest.Option{freq: 5, text: "document", score: score}]
}
]
}
} = search_response

assert is_float(score)
end

test "search with an autocomplete response" do
{:ok, _} =
Snap.Indexes.create(Cluster, @test_index, %{
mappings: %{
properties: %{
name: %{
type: "completion"
}
}
}
})

[
%Action.Index{id: 1, doc: %{name: "Cat"}},
%Action.Index{id: 2, doc: %{name: "Caracal"}},
%Action.Index{id: 3, doc: %{name: "Dog"}}
]
|> Snap.Bulk.perform(Cluster, @test_index, refresh: true)

query = %{
suggest: %{
autocomplete: %{
prefix: "ca",
completion: %{
field: "name"
}
}
}
}

{:ok, search_response} = Search.search(Cluster, @test_index, query)

assert %Snap.SearchResponse{
suggest: %{
"autocomplete" => [
%Snap.Suggest{
text: "ca",
options: [
%Snap.Suggest.Option{
id: "2",
text: "Caracal",
score: caracal_score,
index: index,
source: %{"name" => "Caracal"}
},
%Snap.Suggest.Option{
id: "1",
text: "Cat",
score: cat_score,
index: index,
source: %{"name" => "Cat"}
}
]
}
]
}
} = search_response

assert is_float(caracal_score)
assert is_float(cat_score)
assert is_binary(index)
end

test "count/2 without a query" do
Expand Down
Loading