Elasticsearch (ES) 的 ORM(对象关系映射)库有几个常用的选择,主要用于简化与 Elasticsearch 的交互。以下是一些比较流行的库及其特点:
1. Elasticsearch-py
- 这是 Elasticsearch 的官方 Python 客户端库,不是传统意义上的 ORM,但它提供了与 Elasticsearch 进行交互的丰富 API。你可以使用它来执行索引、搜索和删除等操作。
示例:
python
from elasticsearch import Elasticsearch
# 创建 Elasticsearch 客户端
es = Elasticsearch()
# 索引文档
doc = {
'author': 'Alice',
'text': 'Elasticsearch is a search engine.',
'timestamp': '2024-10-31'
}
es.index(index='test-index', id=1, body=doc)
# 搜索文档
res = es.search(index='test-index', body={'query': {'match': {'author': 'Alice'}}})
print(res['hits']['hits'])
2. elasticsearch-dsl
- 这是一个高层次的 Elasticsearch 客户端库,提供了更友好的 API 和 DSL(领域特定语言),使得与 Elasticsearch 的交互更加简洁。
(360)
示例:
python
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Document, Text, Date, connections
# 创建连接
connections.create_connection(hosts=['localhost'])
class Article(Document):
author = Text()
text = Text()
timestamp = Date()
class Index:
name = 'articles'
# 创建索引
Article.init()
# 创建文档
article = Article(author='Alice', text='Elasticsearch is a search engine.', timestamp='2024-10-31')
article.save()
# 查询文档
s = Article.search().filter('term', author='Alice')
response = s.execute()
print(response)
3. django-elasticsearch-dsl
- 如果你在使用 Django,可以考虑这个库。它将 Django ORM 的模型和 Elasticsearch 索引结合起来,提供了无缝的集成。
示例:
python
from django.db import models
from django_elasticsearch_dsl import Document, fields
from django_elasticsearch_dsl.registries import registry
class Article(models.Model):
author = models.CharField(max_length=100)
text = models.TextField()
timestamp = models.DateTimeField()
@registry.register_document
class ArticleDocument(Document):
class Index:
name = 'articles'
class Django:
model = Article # 关联 Django 模型
# 创建索引
ArticleDocument.init()
# 保存文档
article = Article(author='Alice', text='Elasticsearch is great!', timestamp=datetime.now())
article.save()
# 查询文档
results = ArticleDocument.search().filter('match', author='Alice').execute()
标签:author,Alice,ORM,elasticsearch,import,Article,Elasticsearch,ES
From: https://www.cnblogs.com/pmna/p/18517994