我希望能够在ES索引中存储json对象。下面是我试图存储的一个示例(这是一个序列化的模型,一个发送到ES的请求体):
"{"id":218,"name":"Test2","category_id":1,"address":"Pushkin street","phone":null,"site":null,"location":{"lat":64,"lon":70},"city":"Heaven","description":"Super company","tags":["#test1","#test2"]}"
当我尝试存储它(当然是通过扩展)时,ES返回的错误是:
"{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"failed to parse [location]"}],"type":"mapper_parsing_exception","reason":"failed to parse [location]","caused_by":{"type":"illegal_argument_exception","reason":"unknown property [lat]"}},"status":400}"
如果没有特定的类型映射,我似乎无法做到这一点,比如在文档中:https://www.elastic.co/guide/en/elasticsearch/reference/1.4/mapping-object-type.html
然而,我似乎找不到在模型中提供这种映射的方法。扩展的文档并没有真正说明这一点。所以,我的问题是:我需要它吗?如果需要,怎么需要?
感谢所有反馈。
我假设您的模型是'yii'elasticsearch'ActiveRecord
。你需要描述它的属性:
public function attributes()
{
return [
'name',
'category_id',
'address',
'phone',
'site',
'location',
'city',
'description',
'tags'
];
}
不要忘记配置index()
和type()
。在以下示例中,type
是my_address
。
然后,您需要创建一个具有适当字段映射的索引。以下是您的映射应该是什么样子:
"mappings" : {
"my_address" : {
"properties" : {
"name" : { "type" : "string"},
"category_id" : { "type" : "integer"},
"address" : { "type" : "string"},
"phone" : { "type" : "string"},
"site" : { "type" : "string"},
"location" : { "type" : "geo_point"},
"city" : { "type" : "string"},
"description" : { "type" : "string"},
"tags" : { "type" : "string"}
}
}
}
注意三件事:
- 位置类型为
geo_point
- 标记被声明为
string
。这也将允许它们成为字符串数组 - 我没有包括id字段。如果它是唯一的,我建议您将yii模型的id设置为必要的值(
$model->primaryKey = '123'
)。否则,ES模型的内部id将设置为类似AVDXmfJ3Ou7LzqD1DDMj
的内容,并且还有一个id字段,这不是很方便
我鼓励您仔细研究映射——在配置如何准确分析字符串时,它们非常重要。
更新:您并没有真正描述模型中任何地方的映射。在迁移中执行此操作,类似于在SQL中创建表。
如果您使用ElasticSearch ActiveRecord,您可以定义一个方法来设置映射
Class BookIndex extends yii'elasticsearch'ActiveRecord
{
/**
* sets up the index for this record
*
*/
public static function setUpMapping()
{
$db = static::getDb();
//in case you are not using elasticsearch ActiveRecord so current class extends database ActiveRecord yii/db/activeRecord
// $db = yii'elasticsearch'ActiveRecord::getDb();
$command = $db->createCommand();
/*
* you can delete the current mapping for fresh mapping but this not recommended and can be dangrous.
*/
// $command->deleteMapping(static::index(), static::type());
$command->setMapping(static::index(), static::type(), [
static::type() => [
// "_id" => ["path" => "id", "store" => "yes"],
"properties" => [
'name' => ["type" => "string"],
'author_name' => ["type" => "string"],
'publisher_name' => ["type" => "string"],
'created_at' => ["type" => "long"],
'updated_at' => ["type" => "long"],
'status' => ["type" => "long"],
],
],
]);
}
}
稍后,您只需要在想要应用新映射的任何时候调用此方法。