> For the complete documentation index, see [llms.txt](https://docs.neuron-ai.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.neuron-ai.dev/neuron-v3-zh/rag/vector-store.md).

# 向量存储

Neuron 为你提供可直接使用的组件，用于将你的 Agent 连接到向量数据库。

我们目前为以下向量存储提供第一方支持：

### 内存

这是一个易失性向量存储的实现，它会在当前会话中将你的嵌入保存在机器内存中。当你不需要长期存储生成的嵌入，只需要在当前交互会话期间（或用于本地使用）时，它很有用。

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\MemoryVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new MemoryVectorStore();
    }
}
```

### 文件

文件存储适用于低流量使用场景，或者本地和预发布环境。嵌入文档将存储在文件系统中，并在相似度搜索期间进行处理。

`FileVectorStore` 使用 PHP 生成器从文件系统中读取嵌入文档。在迭代过程中，它始终只会保留不超过 `topK` 个项目在内存中，同时保持非常快的迭代速度。你可以在本地文件系统中存储数千份文档，只需注意你可接受的执行相似度搜索的最大时间。

你也可以使用这个组件，把已经包含某些知识的代理打包到一个文件中。

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\FileVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new FileVectorStore(
            directory: storage_path(),
            topK: 4
        );
    }
}
```

### PHPVector

基于 [`ezimuel/phpvector`](https://github.com/ezimuel/PHPVector)的 PHPVector 适配器。这是一个纯 PHP 的向量数据库，实现了 **HNSW** （分层可导航小世界）用于近似最近邻搜索，以及 **BM25** 用于全文检索。这两种引擎可以组合成一个 **混合搜索** 流程。

你可以使用 composer 安装该组件：

```shellscript
composer require ezimuel/phpvector
```

在 RAG 场景中使用它：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\PHPVector\PHPVector;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyRAG extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new PHPVector(
            path: '/var/data/mydb',
            topK: 5,
        );
    }
}
```

### MariaDB

MariaDB 从 11.7 版本开始支持 VECTOR 列类型。要使此组件正常工作，你需要创建用于存储文档及其相关向量的表。以下是你可以使用的 SQL 脚本：

```sql
CREATE TABLE IF NOT EXISTS rag_documents (
    id UUID NOT NULL PRIMARY KEY,
    content TEXT,
    sourceType VARCHAR(255),
    sourceName VARCHAR(255),
    metadata JSON,
    embedding VECTOR(1536) NOT NULL,
    VECTOR INDEX (embedding)
)
```

以下是在你的 RAG 中使用该组件的方法：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\MariaDBVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new MariaDBVectorStore(
            new \PDO(...), // 或从 ORM 中获取 PDO 实例
        );
    }
}
```

### Pinecone

Pinecone 让为高性能 AI 应用提供长期记忆变得非常容易。它是一个托管的、云原生的向量数据库，具有简单的 API，并且无需基础设施烦恼。Pinecone 以低延迟在数十亿向量的规模下提供最新的、经过过滤的查询结果。

以下是在你的代理中使用 Pinecone 的方法：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\PineconeVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new PineconeVectorStore(
            key: 'PINECONE_API_KEY',
            indexUrl: 'PINECONE_INDEX_URL'
        );
    }
}
```

### Weaviate

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\WeaviateVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new WeaviateVectorStore(
            collection: 'WEAVIATE_COLLECTION_NAME',
            host: 'http://localhost:8080', // 本地或云端 URL
            key: 'WEAVIATE_KEY' // 本地部署时可选
        );
    }
}
```

### Elasticsearch

Elasticsearch 的开源向量数据库提供了一种高效的方式来创建、存储和搜索向量嵌入。要在你的代理实现中将 Elasticseach 用作向量存储，你必须导入官方客户端：

```bash
composer require elasticsearch/elasticsearch
```

以下是使用 Elasticsearch 创建 RAG 的方法：

```php
namespace App\Neuron;

use Elastic\Elasticsearch\ClientBuilder;
use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\ElasticsearchVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        $elasticsearch = ClientBuilder::create()
           ->setHosts(['<elasticsearch-endpoint>'])
           ->setApiKey('<api-key>')
           ->build();
       
        return new ElasticsearchVectorStore(
            client: $elasticsearch,
            index: 'neuron-ai'
        );
    }
}
```

### OpenSearch

Opensearch 是 Elasticsearch 的纯开源替代方案。要在你的代理中使用 Opensearch，你需要安装其官方客户端：

```bash
composer require opensearch-project/opensearch-php
```

一旦你在应用中安装了官方客户端，你就可以返回一个 `OpenSearchVectorStore` 的实例，在你的 RAG 代理中使用：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\OpenSearchVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;
use OpenSearch\GuzzleClientFactory;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        $opensearch = new GuzzleClientFactory()->create([
            'base_uri' => 'http://localhost:9200',
        ]);
        
        return new OpenSearchVectorStore(
            client: $opensearch,
            index: 'neuron-ai',
        );
    }
}
```

### Typesense

[Typesense](https://typesense.org/) 是上述选项的开源替代方案。要在你的代理中使用 Typesense，你需要安装其官方客户端：

```bash
composer require typesense/typesense-php
```

一旦你在应用中安装了官方客户端，你就可以在你的 RAG 代理中返回 TypesenseVectorStore 的一个实例：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\TypesenseVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        $typesense = new \Typesense\Client([
            'api_key' => 'TYPESENSE_API_KEY',
            'nodes' => [
                [
                    'host' => 'TYPESENSE_NODE_HOST',
                    'port' => 'TYPESENSE_NODE_PORT',
                    'protocol' => 'TYPESENSE_NODE_PROTOCOL'
                ],
            ]
        ]);
        
        return new TypesenseVectorStore(
            client: $typesense,
            collection: 'neuron-ai',
            vectorDimension: 1024
        );
    }
}
```

### Qdrant

[Qdrant](https://qdrant.tech/) 是一个具有强大相似度搜索能力的开源向量数据库。要在你的代理中使用 Qdrant，你必须提供一个 `collectionUrl`。这意味着你首先需要在 Qdrant 上创建一个集合，并设置其属性，例如：名称、相似度搜索算法、向量维度等。

一旦你有了集合 URL，你就可以将 `QdrantVectorStore` 实例附加到你的代理上。

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\QdrantVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new QdrantVectorStore(
            collectionUrl: 'http://localhost:6333/collections/neuron-ai/',
            key: 'QDRANT_API_KEY'
        );
    }
}
```

### ChromaDB

[Chroma](https://trychroma.com/) 是一个设计为 AI 应用数据源的开源数据库。要在你的代理中使用 ChromaDB，你必须提供一个内部集合的名称，用于存储嵌入。

一旦你在 Chroma 实例上创建了集合，就可以将 `ChromaVectorStore` 实例附加到代理上：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\ChromaVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new ChromaVectorStore(
            collection: 'neuron-ai',
            //host: 'http://localhost:8000', <-- 这是默认值
            topK: 5
        );
    }
}
```

### Meilisearch

[Meilisearch](https://www.meilisearch.com/) 是一个混合搜索引擎，但 Neuron 的实现将其专门用作嵌入和相似度搜索的向量存储。

该 `indexUid` 参数应为你已创建并配置的 Meilisearch 索引标识符。请确保该索引定义了一个向量字段，其维度与你所使用的嵌入器生成的嵌入大小相匹配。 `嵌入器` 值（例如， `default`）必须对应于你在 Neuron 设置中配置的命名嵌入器，以确保存储的向量与索引配置保持一致。将该组件添加到你的 RAG 中：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\MeilisearchVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        return new MeilisearchVectorStore(
            indexUid: 'MEILISEARCH_INDEXUID',
            host: 'http://localhost:8000', // 或使用云端 URL
            key: 'MEILISEARCH_API_KEY',
            embedder: 'default',
            topK: 5
        );
    }
}
```

### MongoDB

要使用此组件，你需要安装官方的 MongoDB 客户端：

```shellscript
composer require mongodb/mongodb
```

在你的 RAG 或脚本中使用该组件：

```php
namespace App\Neuron;

use NeuronAI\RAG\RAG;
use NeuronAI\RAG\VectorStore\MongoDBVectorStore;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyChatBot extends RAG
{
    ...

    protected function vectorStore(): VectorStoreInterface
    {
        $uri = 'mongodb://localhost:27017';
        $uriOptions = ['serverSelectionTimeoutMS' => 10000];
        $client = new MongoDB\Client($uri, $uriOptions);
        
        return new MongoDBVectorStore(
            client: $client,
            database: 'MONGODB_DATABASE',
            collectionName: 'MONGO_DB_COLLECTION',
            topK: 4
        );
    }
}
```

### 扩展向量存储

如果你想支持一个新的向量存储，你必须实现 `VectorStoreInterface`:

```php
interface VectorStoreInterface
{
    public function addDocument(Document $document): VectorStoreInterface;

    /**
     * @param  Document[]  $documents
     */
    public function addDocuments(array $documents): VectorStoreInterface;

    /**
     * 删除所有匹配过滤条件的文档。
     */
    public function delete(FilterGroup $filters): VectorStoreInterface;

    /**
     * 返回与请求嵌入最相似的文档。
     *
     * @return Document[]
     */
    public function search(SearchRequest $request): iterable;
}
```

之所以有两个不同的方法分别用于添加单个文档或文档集合，是因为许多数据库针对这些用例提供了不同的 API。如果你想交互的数据库没有区别处理这些请求，你可以实现 `addDocuments()` 作为占位符 o `addDocument()`.

该 `search()` 方法应返回带有相似度分数而不是相似度距离的文档列表。如果底层数据库返回的是距离，你可以使用工具类将其转换为分数 `VectorSimilarity`:

```php
namespace App\Neuron\VectorStore;

use NeuronAI\RAG\Document;
use NeuronAI\RAG\VectorSimilarity;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyVectorStore implements VectorStoreInterface
{
    ...


    /**
     * @param float[] $embeddings
     */
    public function search(SearchRequest $request): iterable
    {
        $documents = // 从向量存储中获取文档

        return \array_map(function (Document $document) {
            return $document->setScore(
                VectorSimilarity::similarityFromDistance($similarity)
            );
        }, $documents);
    }
}
```

创建你自己的实现后，你可以像使用其他存储一样在代理中使用它：

```php
namespace App\Neuron;

use App\Neuron\VectorStore\MyVectorStore;
use NeuronAI\Agent;
use NeuronAI\RAG\VectorStore\VectorStoreInterface;

class MyAgent extends Agent
{
    protected function vectorStore(): VectorStoreInterface
    {
        return new MyVectorStore(
            key: 'VECTORSTORE_API_KEY',
            index: 'neuron-ai',
        );
    }
}
```

## 过滤器

### DocumentSchema

`Document` 是贯穿加载、分割、嵌入、存储、检索、中间件和重排序的统一处理对象。其字段通过方法访问。embedding 和 score 是可为空的运行时值；严格 `null` 检查用于表示某个阶段是否生成了它们（`0.0` 仍然是一个有效分数）。

自定义元数据在存储和往返过程中保持无模式。可移植过滤需要向向量存储传递集合级模式：

```php
$schema = DocumentSchema::of(
    DocumentField::string('tenant')->required()->filterable(),
    DocumentField::integer('year')->filterable(),
    DocumentField::strings('tags')->filterable(),
);

$store = new FileVectorStore(schema: $schema);
```

存储会在本地验证声明的值和过滤条件。只有 `sourceType`, `sourceName`以及已声明为可过滤的元数据字段，才是可移植的过滤目标。数组字段支持验证/存储，但除了可移植的可过滤字符串数组外，其他情况都需要原始后端过滤，而字符串数组支持 `containsAny` 和 `containsAll`。已声明的数组必须是非空且同质的列表。一个 `DocumentField` 可以直接传递给过滤工厂，用于具备模式感知的构建。 `neq` 需要一个必填字段，这样缺失字段的行为在不同数据库之间就不会出现差异。RAG 会在嵌入前验证文档。

### 过滤表达式

一旦你用 `DocumentSchema`定义了可过滤字段，就可以在运行时将过滤表达式传递给检索策略。

过滤器是一个可移植、与后端无关的表达式树，会被编译为每个存储的原生语法。这是 **经过过滤的相似度搜索**：元数据过滤器会约束向量相似度结果。请将 **混合搜索** 留给那些结合向量与词法排序的策略。

```php
class MyRAG extends RAG
{
    ...,
    
    protected function retrieval(): RetrievalInterface
    {
        return new SimilarityRetrieval(
            vectorStore: $this->resolveVectorStore(),
            embeddingProvider: $this->resolveEmbeddingsProvider(),
            filters: Filter::gt('year', 2020)
                ->lt('year', date('Y'))
                ->eq('tenant', Tenant::id())
        );
    }
}
```

### 可用过滤器

**`Filter::eq/neq/in/gt/gte/lt/lte(field, value)`** — 低层级比较工厂。

**`Filter::where(field, value)`** 开始一个不可变的流式 `Criteria` ，带有 `where*` 方法用于常见路径。值只能是标量（`null` 会抛出：没有可移植的“缺失”与“空值”语义）；范围值会归一化为 `int|float` （字符串范围不可移植）。带值枚举会归一化为其值，而 `DateTimeInterface` 值会归一化为纪元时间戳。

**`FilterGroup::allOf(...)` / `anyOf(...)`** — 嵌套布尔表达式； `and(...)` / `or(...)` 保持为简短别名。同一运算符的组会被展平，而混合运算符会保留其边界。

**`Filter::containsAny/containsAll(field, values)`** — 用于可过滤 `string[]` 字段的可移植过滤。其他数组类型仍保持后端原生。

**`Filter::raw(StoreClass::class, $fragment)`** — 后端原生逃逸口，并标记其目标存储。带标签的存储会原样传递该片段；其他任何存储的编译器都会抛出异常（在切换存储时大声失败，绝不静默误过滤）。原始片段必须是受信任的、由开发者编写的语法；绝不要将请求值插入其中。

**`FilterScope::merge(...)`** — 将独立提供的强制作用域与根 AND 组合起来。查询表达能力与作用域安全是分开的。

**`FilterGroup::allOf(...)` / `anyOf(...)`** — 嵌套布尔表达式； `and(...)` / `or(...)` 保持为简短别名。同一运算符的组会被展平，而混合运算符会保留其边界。
