備注:
代碼都是使用 elasticsearch/elasticsearch擴(kuò)展操作es糯笙。如果更好方案,歡迎交流
思路:
使用嵌套類型 nested 存儲(chǔ)屬性數(shù)據(jù)
php 代碼
省略......................
設(shè)置mapping信息
$query = [
'index' => 'goods',
'body' => [
'properties' => [
'goods_name' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_smart'
],
'goods_id' => [
'type' => 'long'
],
'attr' => [
'type' => 'nested',
'properties' => [
'attr_name' => [
'type' => 'keyword'
],
'attr_value' => [
'type' => 'keyword'
]
]
]
]
]
];
$this->client->indices()->putMapping($query);
新增商品信息匈织,屬性名稱可以根據(jù)需求記錄屬性id
$query = [
'index' => 'goods',
'id' => 1,
'body' => [
'goods_id' => 1,
'goods_name' => '小米手機(jī) 小米10 68g',
'attr' => [
[
'attr_name' => '操作系統(tǒng)',
'attr_valued' => '安卓'
],
[
'attr_name' => '顏色',
'attr_valued' => '紅色'
],
[
'attr_name' => '屏幕尺寸',
'attr_valued' => '4.5'
],
[
'attr_name' => '重量',
'attr_valued' => '100'
]
]
]
];
$res = $this->client->index($query);
商品搜索,屬性篩選
$query = [
'index' => 'goods',
'body' => [
'query' => [
'bool' => [
'must' => [
[
'nested' => [
'path' => 'attr',
'query' => [
'bool' => [
'must' => [
'match' => [
'attr.attr_name' => '操作系統(tǒng)'
],
'match' => [
'attr.attr_value' => '安卓'
]
]
]
]
]
],
[
'nested' => [
'path' => 'attr',
'query' => [
'bool' => [
'must' => [
'match' => [
'attr.attr_name' => '顏色'
],
'match' => [
'attr.attr_value' => '紅色'
]
]
]
]
]
]
]
]
]
]
];
$data = $this->client->search($query);