根据elasticseach docs,如果我的公司有很多分支机构,并且我想将员工与分支机构相关联,我会这样做
PUT /company
{
"mappings": {
"branch": {},
"employee"{
"_parent": {
"type": "branch"
}
}
}
}
同样可以实现,用户使用 Ruby-on-Rail,如下
class Branch < ActiveRecord::Base
include Elasticsearch::Model
has_many :employees, dependent: :destroy
index_name 'company'
mapping do
indexes :name
end
after_commit lambda { __elasticsearch__.index_document }, on: :create
after_commit lambda { __elasticsearch__.update_document }, on: :update
after_commit lambda { __elasticsearch__.delete_document }, on: :destroy
end
class Employee < ActiveRecord::Base
include Elasticsearch::Model
belongs_to :branch
index_name 'company'
mapping _parent: { type: 'branch' }, _routing: { required: true } do
indexes :name
indexes :email
end
after_commit lambda { __elasticsearch__.index_document(parent: branch_id) }, on: :create
after_commit lambda { __elasticsearch__.update_document(parent: branch_id) }, on: :update
after_commit lambda { __elasticsearch__.delete_document(parent: branch_id) }, on: :destroy
end
module Searchable
INDEX_NAME = 'company'
def create_index!(options={})
client = Branch.__elasticsearch__.client
client.indices.delete index: INDEX_NAME rescue nil if options[:force]
settings = Branch.settings.to_hash.merge Employee.settings.to_hash
mappings = Branch.mappings.to_hash.merge Employee.mappings.to_hash
client.indices.create index: INDEX_NAME,
body: {
settings: settings.to_hash,
mappings: mappings.to_hash }
end
extend self
end
如何设置 elasticsearch rails 以提供以下映射?
PUT /my_index/_mapping/blogpost
{
"blogpost": {
"properties": {
"body": {
"type": "text",
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
}
},
"title": {
"type": "text",
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
}
},
"user": {
"properties": {
"name": {
"type": "text",
"fields": {
"raw": {
"type": "keyword"
}
}
},
"id": {
"type": "long"
}
}
}
}
},
"user": {
"properties": {
"dob": {
"format": "yyyy/MM/dd HH:mm:ss||yyyy/MM/dd||epoch_millis",
"type": "date"
},
"name": {
"type": "text",
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
}
},
"email": {
"type": "text",
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
}
}
}
}
}