Elasticsearch
使用 Elasticsearch 中托管的嵌入模型生成嵌入的方法的演练
实例化ElasticsearchEmbeddings
类的最简单方法是
- 如果使用 Elastic Cloud,则使用
from_credentials
构造函数 - 或者使用任何 Elasticsearch 集群的
from_es_connection
构造函数
!pip -q install langchain-elasticsearch
from langchain_elasticsearch import ElasticsearchEmbeddings
API 参考:ElasticsearchEmbeddings
# Define the model ID
model_id = "your_model_id"
使用from_credentials
进行测试
这需要一个 Elastic Cloud cloud_id
# Instantiate ElasticsearchEmbeddings using credentials
embeddings = ElasticsearchEmbeddings.from_credentials(
model_id,
es_cloud_id="your_cloud_id",
es_user="your_user",
es_password="your_password",
)
# Create embeddings for multiple documents
documents = [
"This is an example document.",
"Another example document to generate embeddings for.",
]
document_embeddings = embeddings.embed_documents(documents)
# Print document embeddings
for i, embedding in enumerate(document_embeddings):
print(f"Embedding for document {i+1}: {embedding}")
# Create an embedding for a single query
query = "This is a single query."
query_embedding = embeddings.embed_query(query)
# Print query embedding
print(f"Embedding for query: {query_embedding}")
使用现有的 Elasticsearch 客户端连接进行测试
这可用于任何 Elasticsearch 部署
# Create Elasticsearch connection
from elasticsearch import Elasticsearch
es_connection = Elasticsearch(
hosts=["https://es_cluster_url:port"], basic_auth=("user", "password")
)
# Instantiate ElasticsearchEmbeddings using es_connection
embeddings = ElasticsearchEmbeddings.from_es_connection(
model_id,
es_connection,
)
# Create embeddings for multiple documents
documents = [
"This is an example document.",
"Another example document to generate embeddings for.",
]
document_embeddings = embeddings.embed_documents(documents)
# Print document embeddings
for i, embedding in enumerate(document_embeddings):
print(f"Embedding for document {i+1}: {embedding}")
# Create an embedding for a single query
query = "This is a single query."
query_embedding = embeddings.embed_query(query)
# Print query embedding
print(f"Embedding for query: {query_embedding}")