跳至主要内容

Elasticsearch

使用 Elasticsearch 中托管的嵌入模型生成嵌入的方法的演练

实例化ElasticsearchEmbeddings类的最简单方法是

  • 如果使用 Elastic Cloud,则使用from_credentials构造函数
  • 或者使用任何 Elasticsearch 集群的from_es_connection构造函数
!pip -q install langchain-elasticsearch
from langchain_elasticsearch import 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}")

此页面是否有帮助?


您也可以留下详细的反馈 在 GitHub 上.