<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title><![CDATA[PHP - Elasticsearch Labs]]></title>
    <description><![CDATA[Articles and tutorials from the Search team at Elastic]]></description>
    <copyright><![CDATA[© 2026. Elasticsearch B.V. All Rights Reserved]]></copyright>
    <image>
      <title><![CDATA[PHP - Elasticsearch Labs]]></title>
      <url>https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt1121c0bf0e8a6e65/6a88da6340a1841030ef456f/search-labs-thumbnail.png</url>
      <link>https://www.elastic.co/cn/search-labs/blog/category/php-programming</link>
    </image>
    <link>https://www.elastic.co/cn/search-labs/blog/category/php-programming</link>
    <atom:link href="https://www.elastic.co/cn/search-labs/rss/category/php-programming.xml" rel="self" type="application/rss+xml"/>
    <language><![CDATA[cn]]></language>
    <lastBuildDate>Mon, 28 Sep 2026 07:03:50 GMT</lastBuildDate>
  <item>
    <title><![CDATA[从 ES|QL 到 PHP 对象]]></title>
    <description><![CDATA[学习如何在 PHP 中执行和管理 ES|QL 查询。请按照本指南将 ES|QL 结果映射到 PHP 对象或自定义类。]]></description>
    <content:encoded><![CDATA[<p>从 elasticsearch-php<a href="https://github.com/elastic/elasticsearch-php/releases/tag/v8.13.0">v8.13.0</a>开始，您可以执行<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/esql.html">ES|QL</a>查询，并将结果映射到<a href="https://www.php.net/manual/en/class.stdclass.php">stdClass</a>或自定义类的 PHP 对象。</p><h2>ES|QL</h2><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/esql.html">ES|QL</a>是 Elasticsearch 8.11.0 中引入的一种新的 Elasticsearch 查询语言。目前，它还处于技术预览阶段。它为过滤、转换和分析存储在 Elasticsearch 中的数据提供了一种强大的方法。</p><p>它利用"管道" (<code>|</code>) 来逐步操作和转换数据。通过这种方法，用户可以进行一系列操作，其中一个操作的输出将成为下一个操作的输入，从而实现复杂的数据转换和分析。</p><p>例如，下面的查询返回<code>sample_data</code> 索引的前 3 个文档（行）：</p>FROM sample_data
| LIMIT 3
<img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt8b0310cb335872b7/6a17d7eab1e113258679f0df/c23aee777bacdf90c63b717fd9458207dfc0511d-864x284.png" alt="ES|QL 生成表格" /><h2>使用案例：官方 PHP 客户端中的 ES|QL 功能</h2><p>为了说明在官方 PHP 客户端中开发的 ES|QL 功能，我们在 Elasticsearch 中存储了一个包含 81,828 本图书（54.4 MB）的<a href="https://github.com/elastic/elasticsearch-php-examples/blob/main/examples/ESQL/data/books.csv">CSV 文件</a>，其中包括以下信息：</p>Title;Descrition;Author;Year;Publisher;Ratings
<p>我们从公开的<a href="https://www.kaggle.com/datasets/mohamedbakhet/amazon-books-reviews">亚马逊图书评论数据集中</a>提取了这份清单。</p><p>我们使用以下 Elasticsearch 映射创建了<code>books</code> 索引：</p>'mappings' : {
    'properties': {
        'title': {
            'type': 'text'
        },
        'description': {
            'type': 'text'
        },
        'author': {
            'type': 'text'
        },
        'year': {
            'type': 'short'
        },
        'publisher': {
            'type': 'keyword'
        },
        'rating': {
            'type': 'half_float'
        }
    }
}
<p><code>rating</code> 值是从 2.9 GB 的<a href="https://www.kaggle.com/datasets/mohamedbakhet/amazon-books-reviews?select=Books_rating.csv">Books_rating.csv</a>文件中提取的评论排名平均值。</p><p><a href="https://github.com/elastic/elasticsearch-php-examples/blob/main/examples/ESQL/bulk.php">在这里</a>，你可以找到我们用来批量导入 Elasticsearch 中所有图书的 PHP 脚本。使用 PHP 8.2.17 进行批量操作耗时 7 秒，占用 28 MB 内存。使用建议的映射后，Elasticsearch 中的索引大小约为 62 MB。</p><h2>将 ES|QL 结果映射到 PHP 对象或自定义类</h2><p>我们可以使用<code>esql()-&gt;query()</code> 端点在 PHP 中执行 ES|QL 查询。查询结果是一个表格数据结构。这在 JSON 中使用<code>columns</code> 和<code>values</code> 字段来表示。在<code>columns</code> 字段中，我们有<code>name</code> 和<code>type</code> 的定义。</p><p>下面是一个 ES|QL 查询示例，用于检索斯蒂芬-金著作中按用户评论排名排序的前 10 本书籍：</p>$query = &lt;&lt;&lt;EOD
    FROM books
    | WHERE author == "Stephen King"
    | SORT rating DESC
    | LIMIT 10
EOD;

$result = $client-&gt;esql()-&gt;query([
    'body' =&gt; ['query' =&gt; $query]
]);
<p>来自 Elasticsearch 的 JSON 结果如下：</p>{
    "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
        ],
        ...
    ]
}
<p>在这个例子中，我们有 6 个与一本书相关的属性（作者、描述、出版商、评分、标题、年份）和 10 个结果，都是斯蒂芬-金的书。</p><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/esql-limitations.html#esql-supported-types">这里</a>列出了 ES|QL 支持的所有类型。</p><p><code>$result</code> 响应对象可以数组、字符串或对象的形式访问（更多信息，请参见<a href="https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/connecting.html#client-usage">此处</a>）。</p><p>使用对象接口，我们可以使用属性和索引访问值。例如，<code>$result-&gt;values[0][4]</code> 返回列表中第一本书（0）的书名（4），<code>$result-&gt;values[1][3]</code> 返回第二本书（1）的等级分（3），等等。请记住，PHP 中数组的索引是从 0 开始的。</p><p>对于某些使用情况，这个接口已经足够好了，但大多数情况下，我们希望得到一个对象数组的结果。</p><p>要将结果映射到对象数组中，我们可以使用 elasticsearch-php 的新功能<a href="https://github.com/elastic/elasticsearch-php/issues/1398">mapTo()。</a></p><p>该功能可直接在<a href="https://github.com/elastic/elasticsearch-php/blob/main/src/Response/Elasticsearch.php">Elasticsearch 响应对象</a>中使用。这意味着您可以通过以下方式访问它：</p>$books = $result-&gt;mapTo(); // Array of stdClass
foreach ($books as $book) {
    printf(
        "%s, %s, %d, Rating: %.2f\n",
        $book-&gt;author,
        $book-&gt;title,
        $book-&gt;year,
        $book-&gt;rating
    );
}
<p>如果您有一个自定义的图书类，可以使用它来映射结果，如下所示：</p>class Book
{
    public string $author;
    public string $title;
    public string $description;
    public int $year;
    public float $rating;
}

$books = $result-&gt;mapTo(Book::class); // Array of Book
<p>如果您的类除了 ES|QL 结果中包含的属性外还有其他属性，这也同样有效。<code>mapTo()</code> 函数将只使用作为 ES|QL 结果列返回的属性。</p><p>您可以<a href="https://github.com/elastic/elasticsearch-php-examples/tree/main/examples/ESQL">在此</a>下载本文中报告的所有示例。</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/esql-php-map-object-class</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/esql-php-map-object-class</guid>
    <category><![CDATA[ES|QL]]></category>
    <category><![CDATA[PHP]]></category>
    <dc:creator><![CDATA[Enrico Zimuel]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt99f5ab85c0713977/6a17d7ebfbc5f8072b491918/aea56270f48cb64130d1b515b983434e0960dc2f-500x500.png" length="0" type="image/png"/>
    <pubDate>Mon, 08 Apr 2024 00:00:00 GMT</pubDate>
  </item>
  </channel>
</rss>