在这篇文章中,我们将使用 Qwen3 来针对数据进行向量搜索。我们将对数据使用 qwen3 嵌入模型来进行向量化,并使用 Qwen3 来对它进行推理。在阅读这篇文章之前,请阅读之前的文章 "如何使用 Ollama 在本地设置并运行 Qwen3"。
安装
Elasticsearch 及 Kibana
如果你还没有安装自己的 Elasticsearch 及 Kibana,那么请阅读这篇文章 "使用 start-local 脚本在本地运行 Elasticsearch" 来进行安装。在默认的情况下,他没有 SSL 的配置:
markdown
``
1. $ curl -fsSL https://elastic.co/start-local | sh
3. ______ _ _ _
4. | ____| | | | (_)
5. | |__ | | __ _ ___| |_ _ ___
6. | __| | |/ _` / __| __| |/ __|
7. | |____| | (_| \__ \ |_| | (__
8. |______|_|\__,_|___/\__|_|\___|
9. -------------------------------------------------
10. 🚀 Run Elasticsearch and Kibana for local testing
11. -------------------------------------------------
13. ℹ️ Do not use this script in a production environment
15. ⌛️ Setting up Elasticsearch and Kibana v9.1.2-arm64...
17. - Generated random passwords
18. - Created the elastic-start-local folder containing the files:
19. - .env, with settings
20. - docker-compose.yml, for Docker services
21. - start/stop/uninstall commands
22. - Running docker compose up --wait
24. [+] Running 6/6
25. ✔ Network elastic-start-local_default Created 0.1s
26. ✔ Volume "elastic-start-local_dev-kibana" Create... 0.0s
27. ✔ Volume "elastic-start-local_dev-elasticsearch" Created 0.0s
28. ✔ Container es-local-dev Healthy 22.0s
29. ✔ Container kibana-local-settings Exited 21.9s
30. ✔ Container kibana-local-dev Healthy 31.9s
32. 🎉 Congrats, Elasticsearch and Kibana are installed and running in Docker!
34. 🌐 Open your browser at http://localhost:5601
36. Username: elastic
37. Password: u06Imqiu
39. 🔌 Elasticsearch API endpoint: http://localhost:9200
40. 🔑 API key: QzNJQnA1Z0JiSkRyN2UwaUk3VFQ6dXFrdkFvRkt1UXlJX2Z1bm5qblpndw==
43. Learn more at https://github.com/elastic/start-local
``AI写代码
在我安装完毕后,我得到的最新的 Elasticsearch 版本是 9.1.2。
写入数据到 Elasticsearch
我们使用如下的代码把数据写入到 Elasticsearch:
elasticsearch_qwen3.py
ini
`
1. from langchain_community.vectorstores import ElasticsearchStore
2. from langchain_community.embeddings import OllamaEmbeddings
4. # Replace with your actual Elasticsearch endpoint
5. ELASTICSEARCH_URL = "http://localhost:9200"
6. INDEX_NAME = "my_embeddings_index"
8. # Initialize Ollama embeddings (you can specify model if needed)
9. embeddings = OllamaEmbeddings(model="qwen3")
11. # Create ElasticsearchStore index
12. vectorstore = ElasticsearchStore(
13. embedding=embeddings,
14. es_url=ELASTICSEARCH_URL,
15. index_name=INDEX_NAME,
16. es_user = "elastic",
17. es_password = "u06Imqiu"
18. )
20. # Example: Add documents to the index
21. str1 = "阿里巴巴(中国)有限公司成立于2007年03月26日,法定代表人蒋芳"
22. str2 = "百度是拥有强大互联网基础的领先AI公司。百度愿景是:成为最懂用户,并能帮助人们成长的全球顶级高科技公司。于2000年1月1日在中关村创建了百度公司"
24. docs = [ str1, str2 ]
25. vectorstore.add_texts(docs)
27. print(f"Index '{INDEX_NAME}' created and documents added.")
`AI写代码
我们需要安装如下的 Python 包:
go
`pip install langchain_community`AI写代码
在上面,我们使用 qwen3 嵌入模型把输入的句子进行向量化。在这里,我们可以使用其它的任何嵌入模型。 运行以上的代码:
go
`python3 elasticsearh_qwen3.py`AI写代码
vbnet
`
1. $ python3 elasticsearch_qwen3.py
2. Index 'my_embeddings_index' created and documents added.
`AI写代码
我们可以在 Kibana 中进行查看:

我们可以看到有两个文档被写入。


这个是因为我们的模型 qwen3:8b 是 4096 维的。
从上面我们也可以看出来所生成的向量。我们可以通过如下的命令来查看它的 mapping:
bash
`GET my_embeddings_index/_mapping`AI写代码
bash
`
1. {
2. "my_embeddings_index": {
3. "mappings": {
4. "properties": {
5. "metadata": {
6. "type": "object"
7. },
8. "text": {
9. "type": "text",
10. "fields": {
11. "keyword": {
12. "type": "keyword",
13. "ignore_above": 256
14. }
15. }
16. },
17. "vector": {
18. "type": "dense_vector",
19. "dims": 4096,
20. "index": true,
21. "similarity": "cosine",
22. "index_options": {
23. "type": "bbq_hnsw",
24. "m": 16,
25. "ef_construction": 100,
26. "rescore_vector": {
27. "oversample": 3
28. }
29. }
30. }
31. }
32. }
33. }
34. }
`AI写代码
我们可以看到有一个叫做 text 及 vector 的字段。
我们可以使用如下的命令来对它进行向量搜索:
elasticsearch_qwen3.py
ini
`
1. from langchain_community.vectorstores import ElasticsearchStore
2. from langchain_community.embeddings import OllamaEmbeddings
4. # Replace with your actual Elasticsearch endpoint
5. ELASTICSEARCH_URL = "http://localhost:9200"
6. INDEX_NAME = "my_embeddings_index"
8. # Initialize Ollama embeddings (you can specify model if needed)
9. embeddings = OllamaEmbeddings(model="qwen3")
11. # Create ElasticsearchStore index
12. vectorstore = ElasticsearchStore(
13. embedding=embeddings,
14. es_url=ELASTICSEARCH_URL,
15. index_name=INDEX_NAME,
16. es_user = "elastic",
17. es_password = "u06Imqiu"
18. )
20. if not vectorstore.client.indices.exists(index=INDEX_NAME):
21. print(f"Index '{INDEX_NAME}' already exists.")
23. # Example: Add documents to the index
24. str1 = "阿里巴巴(中国)有限公司成立于2007年03月26日,法定代表人蒋芳"
25. str2 = "百度是拥有强大互联网基础的领先AI公司。百度愿景是:成为最懂用户,并能帮助人们成长的全球顶级高科技公司。于2000年1月1日在中关村创建了百度公司"
27. docs = [ str1, str2 ]
28. vectorstore.add_texts(docs,
29. bulk_kwargs={
30. "chunk_size": 300,
31. "max_chunk_bytes": 4096
32. })
34. print(f"Index '{INDEX_NAME}' created and documents added.")
36. results = vectorstore.similarity_search(
37. query=" alibaba法定代表人是谁"
38. # k=1
39. # filter=[{"term": {"metadata.source.keyword": "tweet"}}],
40. )
42. # print(results, len(results))
44. for res in results:
45. print(f"* {res.page_content}")
`AI写代码
运行上面的代码:
go
`
1. $ python3 elasticsearch_qwen3.py
2. * 阿里巴巴(中国)有限公司成立于2007年03月26日,法定代表人蒋芳
3. * 百度是拥有强大互联网基础的领先AI公司。百度愿景是:成为最懂用户,并能帮助人们成长的全球顶级高科技公司。于2000年1月1日在中关村创建了百度公司
`AI写代码
我们把 query 改为:
ini
`
1. results = vectorstore.similarity_search(
2. query="中国的搜索引擎公司是哪个"
3. # k=1
4. # filter=[{"term": {"metadata.source.keyword": "tweet"}}],
5. )
`AI写代码
go
`
1. $ python3 elasticsearch_qwen3.py
2. * 百度是拥有强大互联网基础的领先AI公司。百度愿景是:成为最懂用户,并能帮助人们成长的全球顶级高科技公司。于2000年1月1日在中关村创建了百度公司
3. * 阿里巴巴(中国)有限公司成立于2007年03月26日,法定代表人蒋芳
`AI写代码
我们把搜索的 query 改为:
ini
`
1. results = vectorstore.similarity_search(
2. query="淘宝"
3. # k=1
4. # filter=[{"term": {"metadata.source.keyword": "tweet"}}],
5. )
`AI写代码
go
`
1. $ python3 elasticsearch_qwen3.py
2. * 阿里巴巴(中国)有限公司成立于2007年03月26日,法定代表人蒋芳
3. * 百度是拥有强大互联网基础的领先AI公司。百度愿景是:成为最懂用户,并能帮助人们成长的全球顶级高科技公司。于2000年1月1日在中关村创建了百度公司
`AI写代码
ini
`
1. results = vectorstore.similarity_search(
2. query="阿里巴巴的法人代表"
3. # k=1
4. # filter=[{"term": {"metadata.source.keyword": "tweet"}}],
5. )
`AI写代码
go
`
1. $ python3 elasticsearch_qwen3.py
2. * 阿里巴巴(中国)有限公司成立于2007年03月26日,法定代表人蒋芳
3. * 百度是拥有强大互联网基础的领先AI公司。百度愿景是:成为最懂用户,并能帮助人们成长的全球顶级高科技公司。于2000年1月1日在中关村创建了百度公司
`AI写代码