use Elasticsearch\ClientBuilder;
require 'vendor/autoload.php';
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'analysis' => [
'char_filter' => [
'remove_spaces' => [
'type' => 'pattern_replace',
'pattern' => '\\s+',
'replacement' => '-'
],
'convert_amp' => [
'type' => 'pattern_replace',
'pattern' => '&',
'replacement' => 'and'
]
],
'analyzer' => [
'my_analyzer' => [
'char_filter' => ['remove_spaces', 'convert_amp'],
'tokenizer' => 'keyword',
'filter' => ['lowercase', 'asciifolding']
]
]
]
],
'mappings' => [
'my_type' => [
'properties' => [
'brand' => [
'type' => 'string',
'fields' => [
'keyword' => [
'type' => 'string',
'analyzer' => 'my_analyzer',
'index_options' => 'docs',
]
]
],
'color' => [
'type' => 'string',
'fields' => [
'keyword' => [
'type' => 'string',
'analyzer' => 'my_analyzer',
'index_options' => 'docs',
]
]
],
'category' => [
'type' => 'string',
'fields' => [
'keyword' => [
'type' => 'string',
'analyzer' => 'my_analyzer',
'index_options' => 'docs',
]
]
],
'id' => [
'type' => 'integer',
]
]
]
]
]
];
$client->indices()->create($params);
$items = [
[
'id' => 1,
'category' => 'Jackets',
'brand' => 'Tommy Hilfiger',
'color' => 'Dark Red'
],
[
'id' => 2,
'category' => 'Jeans',
'brand' => 'Tommy Jeans',
'color' => 'Navy'
],
[
'id' => 3,
'category' => 'Shirts',
'brand' => 'Tommy Hilfiger',
'color' => 'Maroon'
],
[
'id' => 4,
'category' => 'Trousers',
'brand' => 'Tommy Jeans',
'color' => 'Pale Grey'
],
[
'id' => 5,
'category' => 'Shirts',
'brand' => 'Tommy Hilfiger',
'color' => 'Grey'
],
[
'id' => 6,
'category' => 'Sneakers',
'brand' => 'Tommy Jeans',
'color' => 'Grey'
],
[
'id' => 7,
'category' => 'Sneakers',
'brand' => 'Tommy Jeans',
'color' => 'Grey'
],
[
'id' => 8,
'category' => 'Jeans',
'brand' => 'Tommy Jeans',
'color' => 'Black'
],
[
'id' => 9,
'category' => 'Jeans',
'brand' => 'Tommy & Jeans',
'color' => 'Pale Grey'
],
[
'id' => 10,
'category' => 'Coats & Jackets',
'brand' => 'Très Commas',
'color' => 'Dark Grey'
]
];
foreach ($items as $item) {
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => $item['id'],
'body' => [
'brand' => $item['brand'],
'color' => $item['color'],
'category' => $item['category'],
]
];
$client->index($params);
}
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'bool' => [
'must' => []
]
],
'aggs' => [
'brands' => [
'terms' => [
'field' => 'brand.keyword',
'order' => [
'_term' => 'asc'
]
],
'aggs' => [
'keywords' => [
'terms' => [
'field' => 'brand',
'order' => [
'_term' => 'asc'
]
]
]
],
],
'categories' => [
'terms' => [
'field' => 'category.keyword',
'order' => [
'_term' => 'asc'
]
]
],
'colors' => [
'terms' => [
'field' => 'color.keyword',
'order' => [
'_term' => 'asc'
]
]
]
],
'sort' => [
'category.keyword' => 'asc'
]
]
];
$response = $client->search($params);
print_r($response['aggregations']);