【es数据库】python 使用Elasticsearch数据库

es 数据库

Elasticsearch是一个开源的高扩展性搜索引擎,它可以快速地存储、搜索和分析大量的数据。
使用Python语言和Elasticsearch,可以轻松地创建和操作“数据库”和“数据库表”,而且具备分布式和高扩展性的特点,适用于大规模数据存储与搜索场景。

ES数据库保存数据的格式是文件形式的吗?

ES是一种文档数据库,它并不像关系型数据库一样将每张表的每条记录都保存在表里面,而是将所有文档存储在一个索引中。每个文档都是一个JSON结构,包含多个字段。ES还支持对文档进行全文检索和聚合查询等高级功能。

在存储上,ES将每个索引分成多个分片,每个分片都是一个Lucene实例。每个文档被存储到其中一个分片中,根据文档ID生成一个唯一标识符来定位分片。为了提高性能,ES会在内存中缓存热点数据,并使用文件系统缓存来减少IO操作。

1. 创建“数据库” | 索引(index)

在Elasticsearch中,“数据库”被封装为索引(Index),可以通过以下代码来创建一个索引:

# 首先导入了Elasticsearch模块
from elasticsearch import Elasticsearch

# 创建es数据库句柄
es = Elasticsearch()

# 接着定义了一个索引名称
index_name = "myindex"

# 通过`es.indices.exists()`方法来判断索引是否存在
if not es.indices.exists(index_name):
	# 如果索引不存在,则通过`es.indices.create()`方法来创建索引
    es.indices.create(index=index_name)

2. 创建“数据库表” | 文档类型(doc_type)

在Elasticsearch中,每个索引可以包含多个文档类型(Type),可以通过以下代码来创建一个文档类型:

# `es.indices.put_mapping()`方法,在指定的索引上创建了一个名称为`type_name`的文档类型,并定义了文档类型中的字段
es.indices.put_mapping(
   index=index_name, # 在指定的索引index_name上创建
   body={   # 文档中的字段
       "properties": {
           "field1": {
               "type": "keyword"
           },
           "field2": {
               "type": "text"
           }
       }
   },
   doc_type=type_name  # 文档名称为type_name  
)

3. 创建“数据库表字段”

在上述代码中,通过body参数定义了文档类型中的字段。其中,"type": "keyword"表示该字段类型为字符串,且不需要分词。"type": "text"表示该字段类型为字符串,且需要分词。

4. 常用的ES数据库操作

插入数据 | index | res [‘created’]

doc_id = 1
doc = {
    "field1": "value1",
    "field2": "value2"
}
res = es.index(index=index_name, doc_type=type_name, id=doc_id, body=doc)
if res["created"]:
    print("Document created successfully")

查询数据 | get | res[’ _source’]

res = es.get(index=index_name, doc_type=type_name, id=doc_id)
doc = res["_source"]

更新数据 | update | res[‘result’]

doc_id = n;
doc = {
    "field1": "new_value1"
}
res = es.update(index=index_name, doc_type=type_name, id=doc_id, body={"doc": doc})
if res["result"] == "updated":
    print("Document updated successfully")

删除数据 | delete | res[“result”]

res = es.delete(index=index_name, doc_type=type_name, id=doc_id)
if res["result"] == "deleted":
    print("Document deleted successfully")
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值