我正在尝试在具有 product_name、exported_at 和 category_id 等字段的 Elasticsearch(7.1 版)索引上编写搜索 DSL 查询。
从文档中我了解到,我需要使用通配符、范围来搜索日期字段和术语来过滤所需的 category_id。
示例:我需要过滤其 SQL 为的数据:
SELECT * from products table
WHERE product_name LIKE '%geography%'
AND exported_at >= '2020-01-01' AND exported_at <= '2020-12-31'
AND category_id IN [10,20,30,40]
更新代码如下:
// Creating new index
$params = [
'index' => PS_ELASTIC_INDEX,
'body' => [
'mappings' => [
'properties' => ['wc_product_name' => ["type" => "wildcard"]]
],
]
];
$response_create = $this->client->indices()->create($params);
//Storing data to the Index
//$rows contain the data fetch from the DB
foreach($rows as $row ) {
$data['body'][] = [
'id' => $row->id,
'wc_product_name' => $row->product_name,
'category_id' => $row->category_id,
'exported_at' => $row->exported_at,
]
}
//Search the Elastic search index
$keyword = $requestVars['product_name'];
$filters = [];
$filters[] = [
'wildcard' => [
'wc_product_name' => [
'value' => '*'.$keyword.'*',
],
]
];
$filters[] = [
"range" => [
"exported_on" => [
"gte" => $requestVars['date_from'],
"lte" => $requestVars['date_to'],
"boost" => 2.0
]
],
];
if(!empty($requestVars['categories'])) {
$filters[] = [
"terms" => [
"category_id" => $requestVars['categories'],
"boost" => '1.0'
],
];
}
$params = [
'index' => PS_ELASTIC_INDEX,
'body' => [
'query' => [
'bool' => [ 'filter' => $filters ]
]
]
];
$data = $this->client->search($params);
现在的问题是,如果使用像“地理”这样的单个词作为它工作的产品名称,搜索就可以工作,而搜索像“亚洲地理”这样的多个词将不起作用。