如何使用Postgrex扩展?

时间:2017-09-28 08:07:20

标签: elixir phoenix-framework ecto

我正在尝试使用Postgrex提供的tsvector扩展程序。但是我如何在我的Phoeinx项目中实际使用它呢?这是我在dev.exs中的设置

config :project, Project.Repo,
  adapter: Ecto.Adapters.Postgres,
  username: "postgres",
  password: "postgres",
  database: "project_dev",
  hostname: "localhost",
  pool_size: 10,
  extensions: [{Postgrex.Extensions.TSVector}]

这是架构

  schema "branches" do
    field :address, :string
    field :tags, {:array, :string}
    field :document, Postgrex.Extensions.TSVector

    belongs_to :bank, Bank

    timestamps()
  end

这不应该给我一个新类型TSVector吗?我收到以下错误

** (ArgumentError) invalid or unknown type Postgrex.Extensions.TSVector for field :document

更新

我尝试将架构设置为以下

field :document, {:array, Postgrex.Lexeme}

在从数据库中重新获取值时,我收到以下错误 ** (UndefinedFunctionError) function Postgrex.Lexeme.type/0 is undefined or private

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。默认情况下,tsvector扩展程序在此拉取请求后包含/加载Postgrex:https://github.com/elixir-ecto/postgrex/pull/284,因此无需在:extensions配置中添加任何Project.Repo选项。

我在这样的迁移中创建了列:

def change do
  alter table(:diagnoses) do
    add :search_tsvector, :tsvector
  end

  execute "UPDATE diagnoses SET search_tsvector = to_tsvector('english', concat_ws(' ', description, icd10_code))"

  create index(:diagnoses, [:search_tsvector], using: :gin)
end

之后,事实证明您不能简单地将:tsvector添加到模块架构中,因为不存在:tsvector Ecto类型(仅Postgrex类型,因为延期)。

要在我的架构中使用这个新列,我需要添加一个仅具有默认样板定义的自定义Ecto类型:

defmodule MyApp.Ecto.Types.TSVectorType do
  @behaviour Ecto.Type

  def type, do: :tsvector

  def cast(tsvector), do: {:ok, tsvector}

  def load(tsvector), do: {:ok, tsvector}

  def dump(tsvector), do: {:ok, tsvector}
end

之后,您可以在模块schema中包含此类型:

schema "diagnoses" do
  field :icd10_code, :string
  field :description, :string
  field :search_tsvector, MyApp.Ecto.Types.TSVectorType

  timestamps_with_deleted_at()
end

我实现了搜索此tsvector字段,如下所示:

defp filter_by(query, :search_string, %{search_string: search_string} = args) do
  tsquery_string = StringHelpers.to_tsquery_string(search_string)

  from d in query,
    where: fragment("? @@ to_tsquery('english', ?)", d.search_tsvector, ^tsquery_string)
end
相关问题