从 elasticsearch-php v8.13.0 开始,您可以执行 ES|QL 查询,并将结果映射到 PHP 的 stdClass 对象或自定义类。
ES|QL 是 Elasticsearch 8.11.0 引入的一种新的 Elasticsearch 查询语言。目前,它处于技术预览阶段。它提供了一种强大的方式来过滤、转换和分析存储在 Elasticsearch 中的数据。
它利用了 "管道符" (|
) 以逐步的方式操作和转换数据。这种方法允许用户组合一系列操作,其中一个操作的输出成为下一个操作的输入,从而实现复杂的数据转换和分析。
例如,以下查询返回 sample_data
索引的前3个文档(行):
FROM sample_data
| LIMIT 3
为了演示官方 PHP 客户端中开发的 ES|QL 功能,我们将来自 Amazon 图书评论数据集 的 81,828 本图书(54.4 MB)存储在 Elasticsearch 中,其中包括以下信息:
Title;Descrition;Author;Year;Publisher;Ratings
我们从中提取了这个列表。
我们创建了一个 books
索引,并使用以下 Elasticsearch 映射:
'mappings' : {
'properties': {
'title': {
'type': 'text'
},
'description': {
'type': 'text'
},
'author': {
'type': 'text'
},
'year': {
'type': 'short'
},
'publisher': {
'type': 'keyword'
},
'rating': {
'type': 'half_float'
}
}
}
rating
值是从 2.9 GB 的 Books_rating.csv 文件中取得的排名评价的平均值。
这里 您可以找到我们用来批量导入所有图书到 Elasticsearch 的 PHP 脚本。使用 PHP 8.2.17 执行批量操作耗时 7 秒,内存占用 28 MB。根据建议的映射,在 Elasticsearch 中的索引大小约为 62 MB。
我们可以使用 esql()->query()
端点在 PHP 中执行 ES|QL 查询。这个查询的结果是一个表格数据结构。这是用 columns
和 values
字段的 JSON 表示的。在 columns
字段中,我们有 name
和 type
定义。
以下是检索由 Stephen King 撰写的前10本书并按用户评分排序的 ES|QL 查询示例:
$query = <<<EOD
FROM books
| WHERE author == "Stephen King"
| SORT rating DESC
| LIMIT 10
EOD;
$result = $client->esql()->query([
'body' => ['query' => $query]
]);
来自 Elasticsearch 的 JSON 结果如下所示:
{
"columns": [
{ "name": "author", "type": "text" },
{ "name": "description", "type": "text" },
{ "name": "publisher", "type": "keyword" },
{ "name": "rating", "type": "double" },
{ "name": "title", "type": "text" },
{ "name": "year", "type": "integer" }
],
"values": [
[
"Stephen King",
"The author ...",
"Turtleback",
5.0,
"How writers write",
2002
],
[
"Stephen King",
"In Blockade Billy, a retired coach...",
"Simon and Schuster",
5.0,
"Blockade",
2010
],
[
"Stephen King",
"A chilling collection of twenty horror stories.",
"Signet Book",
4.55859375,
"Night Shift (Signet)",
1979
],
...
]
}
在这个例子中,我们有 6 个属性(author、description、publisher、rating、title、year)与一本书相关联,以及 10 个结果,都是 Stephen King 撰写的书。
ES|QL 中所有支持的类型列表在 这里。
$result
响应对象可以作为数组、字符串或对象访问(有关更多信息,请参见此处)。
使用对象接口,我们可以使用属性和索引访问值。例如,$result->values[0][4]
返回列表中第一本书(0)的标题(4),$result->values[1][3]
返回列表中第二本书(1)的排名分数(3),以此类推。请记住,在 PHP 中数组的索引从零开始。
这种接口对于某些用例可能已经足够了,但大多数情况下,我们希望将结果映射为对象数组。
要将结果映射到对象数组中,我们可以使用 elasticsearch-php 的新 mapTo() 功能。
这个函数直接在 Elasticsearch 响应对象 中可用。这意
味着您可以这样访问它:
$books = $result->mapTo(); // Array of stdClass
foreach ($books as $book) {
printf(
"%s, %s, %d, Rating: %.2f\n",
$book->author,
$book->title,
$book->year,
$book->rating
);
}
如果您有一个自定义的 Book 类,您可以使用它来映射结果,如下所示:
class Book
{
public string $author;
public string $title;
public string $description;
public int $year;
public float $rating;
}
$books = $result->mapTo(Book::class); // Array of Book
如果您的类除了 ES|QL 结果中包含的属性外还有其他属性,这也是有效的。mapTo()
函数将仅使用 ES|QL 结果中返回的属性。
您可以在 这里 下载本文中提到的所有示例。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。