PHP 8.6可以通过PostgreSQL的tsvector、websearch_to_tsquery和ts_rank_cd实现英文文章检索:数据库保存带权重的检索向量,PHP只传查询文本,再按相关度和稳定编号排序。示例要求已启用pgsql扩展,并使用PostgreSQL内置english配置;它不提供中文分词。
为英文内容生成带权重的检索向量
CREATE TABLE search_articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
document tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'D')
) STORED
);
CREATE INDEX search_articles_doc_idx ON search_articles USING GIN (document);
INSERT INTO search_articles(title,body) VALUES
('PHP database guide','Parameter binding for reliable database queries.'),
('Search guide','PostgreSQL ranks matching documents with text search.');
显式指定english,使生成表达式不依赖会话默认检索配置。标题设a权重、正文设d权重,实际权重取舍仍需结合内容评估;gin索引用于匹配过滤,不会直接提供相关度排序。

PostgreSQL官方文档:生成检索向量及创建全文索引
把用户检索文本作为值传入
<?php $dsn = getenv('PG_DSN') ?: '';
if ($dsn === '') { throw new RuntimeException('PG_DSN is required'); }
$db = pg_connect($dsn);
if ($db === false) { throw new RuntimeException('Database connection failed'); }
$term = trim($argv[1] ?? 'database queries');
if ($term === '' || strlen($term) > 300) { throw new InvalidArgumentException('Invalid search text'); }
$sql = <p>websearch_to_tsquery按网页搜索习惯解析引号、OR和减号等输入;参数化查询隔离的是SQL语法,不代表所有词都有有效词项。空白、停用词或过长输入应在产品层给出可理解提示。</p><p style="text-align:center">@@##@@</p><p style="text-align:center">PostgreSQL官方文档:构造全文检索查询</p><h2>检查排序与真实查询计划</h2><p>运行php search.php "database queries",应返回包含对应词项的行,rank是相关度分值而非概率。再用EXPLAIN (ANALYZE, BUFFERS)查看代表性数据上的查询计划;小表可能选择顺序扫描,不能仅凭这个现象判断GIN失效。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Build MCP servers and clients for PHP applications with the official PHP SDK" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="overflowclass">Build MCP servers and clients for PHP applications with the official PHP SDK</a>
<p class="overflowclass">使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13222" title="Build MCP servers and clients for PHP applications with the official PHP SDK" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>页面展示标题或摘要时按输出环境转义。此示例没有直接输出ts_headline生成的标记,也不把检索文本当作HTML。中文、日文及混合语料需要另外选择合适的检索配置和分词方法,不能只把english改成一个不存在的配置名。</p><p style="text-align:center">@@##@@</p><p style="text-align:center">PostgreSQL官方文档:全文检索结果的相关度排序</p>


php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










