ExTypesense behaviour (ExTypesense v2.0.1)
View SourcePublic API functions to interact with Typesense.
If you want to implement field types for your Ecto schema,
you may need to encode the schema and add the callback get_field_types/0
:
Schema and field types for Ecto
The code below is when you're using it with Ecto schema. Skip this if you just want plain old maps
defmodule App.Person do
use Ecto.Schema
@behaviour ExTypesense
defimpl Jason.Encoder, for: __MODULE__ do
def encode(value, opts) do
value
|> Map.take([:id, :persons_id, :name, :age])
|> Enum.map(fn {key, val} ->
cond do
key === :id -> {key, to_string(Map.get(value, :id))}
key === :persons_id -> {key, Map.get(value, :id)}
true -> {key, val}
end
end)
|> Enum.into(%{})
|> Jason.Encode.map(opts)
end
end
schema "persons" do
field :name, :string
field :age, :integer
field :persons_id, :integer, virtual: true
end
@impl ExTypesense
def get_field_types do
name = __MODULE__.__schema__(:source)
primary_field = name <> "_id"
%{
name: name,
default_sorting_field: primary_field,
fields:
[
%{name: primary_field, type: "int32"},
%{name: "name", type: "string"},
%{name: "age", type: "integer"}
]
}
end
end
Summary
Callbacks
A callback function for creating the schema fields in Typesense.
Callbacks
@callback get_field_types() :: map()
A callback function for creating the schema fields in Typesense.
Where to add
This function should be added in the Ecto Schema that you will be use to import to Typesense.
defmodule MyApp.Accounts.User do
use Ecto.Schema
@behaviour ExTypesense
#... Lots of user-related code + Ecto schema
@impl ExTypesense
def get_field_types do
name = __MODULE__.__schema__(:source)
primary_field = name <> "_id"
%{
name: name,
default_sorting_field: primary_field,
fields:
[
%{name: primary_field, type: "int32"},
%{name: "name", type: "string"},
%{name: "age", type: "integer"}
]
}
end