我想为我所有的 laravel 搜索查询实现弹性搜索。我使用 brew 安装了最新的 Laravel 和最新的 elasticsearch。
curl http://localhost:9200/
给,
{
"name" : "_SFvSGk",
"cluster_name" : "elasticsearch_an398690",
"cluster_uuid" : "xBi3aTDaTkmA6dtzhpOrwg",
"version" : {
"number" : "6.5.4",
"build_flavor" : "oss",
"build_type" : "tar",
"build_hash" : "d2ef93d",
"build_date" : "2018-12-17T21:17:40.758843Z",
"build_snapshot" : false,
"lucene_version" : "7.5.0",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
在这里,我正在使用驱动程序 babenkoivan/scout-elasticsearch-driver
。
型号,
namespace App;
use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
use Searchable;
/**
* @var string
*/
protected $indexConfigurator = CustomerIndexConfigurator::class;
/**
* @var array
*/
protected $searchRules = [
CustomerSearchRule::class
];
/**
* @var array
*/
protected $mapping = [
'properties' => [
'text' => [
'type' => 'text',
'fields' => [
'ref_num' => [
'type' => 'keyword',
]
]
],
]
];
}
搜索规则,
namespace App;
use ScoutElastic\SearchRule;
class CustomerSearchRule extends SearchRule
{
/**
* @inheritdoc
*/
public function buildHighlightPayload()
{
return [
'fields' => [
'ref_num' => [
'type' => 'plain'
]
]
];
}
/**
* @inheritdoc
*/
public function buildQueryPayload()
{
$query = $this->builder->query;
return [
[
'match' => [
'ref_num' => [
'query' => $query,
'boost' => 2
]
]
]
];
}
}
配置器,
namespace App;
use ScoutElastic\IndexConfigurator;
use ScoutElastic\Migratable;
class CustomerIndexConfigurator extends IndexConfigurator
{
use Migratable;
/**
* @var array
*/
protected $settings = [
//
];
}
我有一个记录ref_num
as I50263
。所以当我搜索I50
相同的时候我应该得到这个记录like query
。我尝试了以下所有搜索,但我只得到了完整单词的结果I50263
。
return Customer::search('I50')->get();
// no record
return Customer::search('I50263')->get();
// got record
return Customer::searchRaw([
'query' => [
'bool' => [
'must' => [
'match' => [
'ref_num' => 'I502'
]
]
]
]
]);
// no record
return Customer::searchRaw([
'query' => [
'bool' => [
'must' => [
"match_phrase" => [
"ref_num" => [
"query" => "I50",
"boost" => 1
]
]
]
]
]
]);
// no record
也尝试过字段类型text
。