[AI Embedchain] API手册 Search

.search()允许您通过在您的数据源上基于给定查询执行语义搜索来发现最相关的上下文。请参考下面的函数签名:

使用

基础

参考以下示例了解如何使用搜索API:

代码示例

1
2
3
4
5
6
7
from embedchain import App

app = App()
app.add("https://www.forbes.com/profile/elon-musk")

context = app.search("What is the net worth of Elon?", num_documents=2)
print(context)

高级

使用where参数进行元数据过滤

这是search()API的一个高级示例,它对Pinecone数据库上的元数据进行过滤:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import os

from embedchain import App

os.environ["PINECONE_API_KEY"] = "xxx"

config = {
    "vectordb": {
        "provider": "pinecone",
        "config": {
            "metric": "dotproduct",
            "vector_dimension": 1536,
            "index_name": "ec-test",
            "serverless_config": {"cloud": "aws", "region": "us-west-2"},
        },
    }
}

app = App.from_config(config=config)

app.add("https://www.forbes.com/profile/bill-gates", metadata={"type": "forbes", "person": "gates"})
app.add("https://en.wikipedia.org/wiki/Bill_Gates", metadata={"type": "wiki", "person": "gates"})

results = app.search("What is the net worth of Bill Gates?", where={"person": "gates"})
print("Num of search results: ", len(results))

使用raw_filter参数进行元数据过滤

以下是按Pinecone矢量数据库遵循的原始过滤查询传递元数据过滤的示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import os

from embedchain import App

os.environ["PINECONE_API_KEY"] = "xxx"

config = {
    "vectordb": {
        "provider": "pinecone",
        "config": {
            "metric": "dotproduct",
            "vector_dimension": 1536,
            "index_name": "ec-test",
            "serverless_config": {"cloud": "aws", "region": "us-west-2"},
        },
    }
}

app = App.from_config(config=config)

app.add("https://www.forbes.com/profile/bill-gates", metadata={"year": 2022, "person": "gates"})
app.add("https://en.wikipedia.org/wiki/Bill_Gates", metadata={"year": 2024, "person": "gates"})

print("Filter with person: gates and year > 2023")
raw_filter = {"$and": [{"person": "gates"}, {"year": {"$gt": 2023}}]}
results = app.search("What is the net worth of Bill Gates?", raw_filter=raw_filter)
print("Num of search results: ", len(results))