2016-08-21 80 views
1

JSONB嵌入式Ecto2模型我不是如何索引嵌入式结构为JSONB与Ecto2/Postgres的9.4+索引Postgres里9.4+

存储我有使用embeds_one和embeds_many两个嵌入式结构架构清晰。它们是ecto:在Postgres中以JSONB表示的地图字段。我想知道如何确保他们被索引(使用杜松子?)进行快速查询?我不知道这是否自动发生,如果我需要添加索引到我的迁移,或者如果我需要手动使用psql等。

只是寻求澄清这是如何工作的。 谢谢!

defmodule App.Repo.Migrations.CreateClient 
    def change do 
    create table(:clients) do 
     add :name, :string 
     add :settings, :map 
     add :roles, {:array, :map}, default: [] 
     timestamps() 
    end 

    // This works for normal schema/model fields 
    create index(:clients, [:name], unique: true, using: :gin) 

    // BUT CAN I INDEX MY EMBEDS HERE? 
    // GUESS: 
    create index(:clients, [:settings], using: :gin) 
    end 
end 

defmodule App.Client do 
    schema "client" do 
    field :name, :string 
    embeds_one :settings, Settings // single fixed schema "Settings" model 
    embeds_many :roles, Role  // array of "Role" models 
    end 
end 

defmodule Settings do 
    use Ecto.Model 
    embedded_schema do   // ALSO 
    field :name, :string  // are types relevant?   
    field :x_count, :integer // stored as strings (INDEXED?) 
    field :is_active, :boolean // deserialized via cast? 
    end 
end 

defmodule Role do 
    use Ecto.Model 
    embedded_schema do  
    field :token 
    field :display_english 
    field :display_spanish 
    end 
end 

回答

2

我想你只需要补充一点:

create index(:clients, [:name], unique: true, using: :gin) 

到迁移文件。

;如果索引SQL语句会很复杂,你可以用execute做,所以它会是这样的:

execute("CREATE INDEX clients_name_index ON clients USING GIN (name)") 

我没有测试过,但我相信它应该工作。

+0

对于客户端模型中的顶级字段绝对是正确的,但我询问索引JSONB:map字段 – errata

+0

嗯,去[here](https://www.postgresql.org/docs/current/static /datatype-json.html)并查看'jsonb Indexing'部分,jsonb列的语法与通常的相同,所以我的第一个示例应该工作,除非您为索引添加了一些特定的选项,为此'使用'执行' – JustMichael