增加数据:

使用elasticsearch-dsl库,可以通过以下代码向elasticsearch中添加数据:

from elasticsearch_dsl import connections, Document, Keyword, Text

# 连接elasticsearch
connections.create_connection(hosts=['localhost'])

# 定义数据模型
class Article(Document):
    title = Text()
    content = Text()
    tags = Keyword()

    class Index:
        name = 'article_index'

    def save(self, **kwargs):
        return super().save(**kwargs)

# 创建数据
article = Article(title='Python基础教程', content='Python是一种高级编程语言', tags=['Python', '教程'])
article.save()

删除数据:

使用elasticsearch-dsl库,可以通过以下代码从elasticsearch中删除数据:

from elasticsearch_dsl import connections, Document, Keyword, Text

# 连接elasticsearch
connections.create_connection(hosts=['localhost'])

# 定义数据模型
class Article(Document):
    title = Text()
    content = Text()
    tags = Keyword()

    class Index:
        name = 'article_index'

    def save(self, **kwargs):
        return super().save(**kwargs)

    def delete(self, **kwargs):
        return super().delete(**kwargs)

# 删除数据
article = Article.get(id='1')
article.delete()

修改数据:

使用elasticsearch-dsl库,可以通过以下代码修改elasticsearch中的数据:

from elasticsearch_dsl import connections, Document, Keyword, Text

# 连接elasticsearch
connections.create_connection(hosts=['localhost'])

# 定义数据模型
class Article(Document):
    title = Text()
    content = Text()
    tags = Keyword()

    class Index:
        name = 'article_index'

    def save(self, **kwargs):
        return super().save(**kwargs)

# 修改数据
article = Article.get(id='1')
article.title = 'Python高级教程'
article.save()

查询数据:

使用elasticsearch-dsl库,可以通过以下代码查询elasticsearch中的数据:

from elasticsearch_dsl import connections, Document, Keyword, Text

# 连接elasticsearch
connections.create_connection(hosts=['localhost'])

# 定义数据模型
class Article(Document):
    title = Text()
    content = Text()
    tags = Keyword()

    class Index:
        name = 'article_index'

    def save(self, **kwargs):
        return super().save(**kwargs)

# 查询数据
from elasticsearch_dsl import Search

s = Search(index='article_index').query('match', title='Python')
response = s.execute()

for hit in response:
    print(hit.title)
``
python 增删改查elstaticsearch数据

原文地址: https://www.cveoy.top/t/topic/huta 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录