如何使用Laravel Scout Elasticsearch Driver从Elasticsearch获取文档的自定义字段?

时间:2019-09-13 15:10:36

标签: json elasticsearch custom-fields custom-attributes laravel-scout

下面是我在Laravel项目中使用的Scout Elasticsearch Drive的链接。

https://github.com/babenkoivan/scout-elasticsearch-driver

我有数据库表users,其中包含以下列:

id            Integer
name          String
created_at    DateTime

按照GitHub上的文档,我在User模型中的映射如下所示:

use Searchable; // using Searchable trait.

protected $mapping = [
     'properties' => [
         'name' => [
            'type' => 'text',
            'fields' => [
                'raw' => [
                    'type' => 'keyword',
                ],
            ],
         ],
         'created_at' => [
            'type' => 'date',
            'format' => 'dd-MM-yyyy HH:mm',
            'fields' => [
                'raw' => [
                    'type' => 'keyword',
                ],
            ],
        ],
        // Custom field...
        'created_date' => [
            'type' => 'date',
            'format' => 'dd-MM-yyyy',
            'fields' => [
                'raw' => [
                    'type' => 'keyword',
                ],
            ],
        ],
        // Custom field...
        'created_time' => [
            'type' => 'date',
            'format' => 'HH:mm',
            'fields' => [
                'raw' => [
                    'type' => 'keyword',
                ],
            ],
        ],

     ]
]

下面是toSearchableArray()函数的实现。

public function toSearchableArray()
{
    $array = $this->toArray();

    // Pre-format the custom fields before inserting them into Elasticsearch.
    $array['created_date'] = $this->created_at->format('d-m-Y');
    $array['created_time'] = $this->created_at->format('h:i');

    return $array;
}

使用curl -X GET命令时,我得到以下结果,当然还有自定义字段。

"hits" : [
  {
      "_source" : {
          "id" : 3,
          "name": "John Doe",
          "created_at": "31-12-2018 23:59",
          "created_date": "31-12-2018", // My custom field.
          "created_time": "23:59" // My custom field.
  }
]

在我的控制器中的index()操作中,我使用以下代码查询数据。

public function index() 
{
     return User::search("*")->get();
}

我得到的记录只有原始属性,与数据库表中的那些列相匹配,如下所示。

[
   {
       "id" : 3,
       "name": "John Doe",
       "created_at": "31-12-2018 23:59",
   }
]

请注意,这是Laravel默认提供的JSON响应,用于响应API调用。我的自定义属性created_datecreated_time也确实存在于Elasticsearch中。我怎么也能得到它们?我创建这些自定义字段的原因是要事先在服务器端设置日期和时间的格式,以便客户端无需担心在for循环中设置日期和时间的格式。

当我使用User::search("*")->explain();时,也会在hits.hits._source{}对象中获得自定义字段。

1 个答案:

答案 0 :(得分:0)

这应该直接为您提供来自Elastic Search的结果,而无需与您的相关模型匹配。我认为这就是您的自定义字段丢失的原因。

public function index() 
{
     return User::search("*")->raw();
}

Documentation