【python qdrant 向量数据库 完整示例代码】

测试一下python版本的dqrant向量数据库的效果,完整代码如下:

安装库

复制代码
!pip install qdrant-client>=1.1.1
!pip install -U sentence-transformers

导入

复制代码
from qdrant_client import models, QdrantClient
from sentence_transformers import SentenceTransformer

encoder = SentenceTransformer("all-MiniLM-L6-v2", device="cuda")

准备测试数据集

复制代码
documents = [
    {
        "name": "The Time Machine",
        "description": "A man travels through time and witnesses the evolution of humanity."
        * 8,
        "author": "H.G. Wells",
        "year": 1895,
    },
    {
        "name": "Ender's Game",
        "description": "A young boy is trained to become a military leader in a war against an alien race."
        * 4,
        "author": "Orson Scott Card",
        "year": 1985,
    },
    {
        "name": "Brave New World",
        "description": "A dystopian society where people are genetically engineered and conditioned to conform to a strict social hierarchy."
        * 6,
        "author": "Aldous Huxley",
        "year": 1932,
    },
] * 50000

print(len(documents))

创建存储库

复制代码
qdrant = QdrantClient(":memory:")  # 内存中
# qdrant = QdrantClient(path='./qdrant')  # 存储到本地

在数据库中创建一个collection(类似一个存储桶)

复制代码
qdrant.recreate_collection(
    collection_name="my_books",
    vectors_config=models.VectorParams(
        size=encoder.get_sentence_embedding_dimension(),  # Vector size is defined by used model
        distance=models.Distance.COSINE,
    ),
)

对文档进行向量化

复制代码
import hashlib
from tqdm import tqdm

def sha256(text):

    hash_object = hashlib.sha256()
    hash_object.update(text.encode("utf-8"))
    hash_value = hash_object.hexdigest()
    return hash_value

records = []
bs = 256
for i in tqdm(range(0, len(documents), bs)):
    docs = documents[i : i + bs]
    vectors = encoder.encode(
        [doc["description"] for doc in docs], normalize_embeddings=True
    ).tolist()

    record = [
        models.Record(id=idx, vector=vec, payload=doc)  # sha256(doc['description'])
        for idx, vec, doc in zip(range(i, i + bs), vectors, docs)
    ]

    records.extend(record)

上传到向量数据库中指定的collection

复制代码
qdrant.upload_points(
    collection_name="my_books", points=records, batch_size=128, parallel=12
)

语义搜索

复制代码
query = "Aliens attack our planet"
hits = qdrant.search(
    collection_name="my_books",
    query_vector=encoder.encode(query).tolist(),
    limit=6,
)
for hit in hits:
    print(hit.payload, "score:", hit.score)

条件搜索

search only for books from 21st century

复制代码
hits = qdrant.search(
    collection_name="my_books",
    query_vector=encoder.encode("Tyranic society").tolist(),
    query_filter=models.Filter(
        must=[models.FieldCondition(key="year", range=models.Range(gte=1980))]
    ),
    limit=3,
)
for hit in hits:
    print(hit.payload, "score:", hit.score)

参考官方GitHub

github

colab

相关推荐
偶尔微微一笑14 分钟前
AI网络渗透kali应用(gptshell)
linux·人工智能·python·自然语言处理·编辑器
船长@Quant2 小时前
文档构建:Sphinx全面使用指南 — 基础篇
python·markdown·sphinx·文档构建
喵手2 小时前
从 Java 到 Kotlin:在现有项目中迁移的最佳实践!
java·python·kotlin
liuweidong08022 小时前
【Pandas】pandas DataFrame rsub
开发语言·python·pandas
CH3_CH2_CHO2 小时前
不吃【Numpy】版
开发语言·python·numpy
-曾牛3 小时前
企业级AI开发利器:Spring AI框架深度解析与实战
java·人工智能·python·spring·ai·rag·大模型应用
Light603 小时前
智启未来:深度解析Python Transformers库及其应用场景
开发语言·python·深度学习·自然语言处理·预训练模型·transformers库 |·|应用场景
坤岭3 小时前
Python基础
python
一个天蝎座 白勺 程序猿3 小时前
Python爬虫(5)静态页面抓取实战:requests库请求头配置与反反爬策略详解
开发语言·爬虫·python
一眼青苔3 小时前
python环境使用conda,conda如何升级默认的python版本
开发语言·python·conda