我使用 MongoDB 来存储有关鞋子的信息。每只鞋都有一个标题(字符串),照片(字符串,这是照片的网址),链接(字符串,原始网站的网址),尺寸(字符串数组),颜色(字符串数组)和价格(字符串)和性别(字符串)。
在我的 project/app/models/shoe.rb 文件中,我有:
class Shoe
include Mongoid::Document
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
field :title
field :photo
field :link
field :price
field :gender
field :sizes, type: Array, default: []
field :colors, type: Array, default: []
def as_indexed_json
as_json({only: [:title, :gender, :colors, :price, :sizes]})
end
settings index: { number_of_shards: 1 } do
mappings dynamic: 'false' do
indexes :title, analyzer: 'bulgarian'
indexes :colors, analyzer: 'bulgarian'
indexes :gender, analyzer: 'bulgarian'
end
end
def self.more_like_this(shoe)
__elasticsearch__.search(
{
query: {
bool: {
must: {match_all: { }},
should: [
# {
# more_like_this: {
# fields: ['title'],
# like: [
# {
# _index: 'shoes',
# _type: 'shoe',
# _id: shoe.id
# }
# ],
# boost: 2.0
# }
# },
{
more_like_this: {
fields: ['gender'],
like: [
{
_index: 'shoes',
_type: 'shoe',
_id: shoe.id
}
],
}
}
],
minimum_should_match: 1
}
}
}
)
end
end
# Delete the previous shoes index in Elasticsearch
Shoe.__elasticsearch__.client.indices.delete index: Shoe.index_name rescue nil
# Create the new index with the new mapping
Shoe.__elasticsearch__.client.indices.create \
index: Shoe.index_name,
body: { settings: Shoe.settings.to_hash, mappings: Shoe.mappings.to_hash }
# Index all shoe records from the DB to Elasticsearch
Shoe.import
在 project/config/initializers/elasticsearch.rb 我有:
config = {
host: "http://localhost:9200/",
transport_options: {
request: { timeout: 5 }
},
}
if File.exists?("config/elasticsearch.yml")
config.merge!(YAML.load_file("config/elasticsearch.yml").symbolize_keys)
end
Elasticsearch::Model.client = Elasticsearch::Client.new(config)
unless Shoe.__elasticsearch__.index_exists?
Shoe.__elasticsearch__.create_index! force: true
Shoe.import
end
在 project/config/mongoid.yml 我有:
development:
# Configure available database clients. (required)
clients:
# Defines the default client. (required)
default:
# Defines the name of the default database that Mongoid can connect to.
# (required).
database: cornersport
# Provides the hosts the default client can connect to. Must be an array
# of host:port pairs. (required)
hosts:
- localhost:27017
test:
clients:
default:
database: calceus_test
hosts:
- localhost:27017
options:
read:
mode: :primary
max_pool_size: 1
现在,在 Rails 控制台中,在运行 elasticsearch 的情况下,我调用Shoe.more_like_this(some_shoe_object).results.to_a
它并返回[]
. 首先,我的查询包括注释部分,但是当我没有得到任何结果时,我将其注释掉,尽管数据库中有更多与some_shoe_object
. 它不应该返回一些东西吗?我使用弹性搜索错了吗?我是初学者。请帮忙!