用 python 操作 elasticsearch

python连接 elasticsearch 进行搜索

用 python 操作 elasticsearch 使用的第三方库是 elasticsearch

from elasticsearch import Elasticsearch
# host 是 ES 的主机IP,port 是 ES 的端口号
es = Elasticsearch([{'host': settings.ELASTICSEARCH_HOST, 'port': settings.ELASTICSEARCH_PORT}],
                           timeout=3600)  # 连接es
body = \
    {
        "query": {
            "bool": {
                "filter": {
                    "terms": {"type_id": [1, 3, 4, 5, 6]}
                },
                "must_not": {
                    "terms": {
                        "_id": must_not_list
                    }
                }
                ,
                "must": {
                    "range": {
                        "video_date": {
                            "gte": "now-24h+8h",
                            "lte": "now+8h"
                        }
                    }
                }
            }
        },
        "sort": {"video_like": {"order": "desc"}},
        "from": start,
        "size": size
    }
   # 搜索是调用 search 方法。body是 搜索的body体,index是要搜索的索引名称,返回结果的结构是 json 格式,和直接操作es返回的结果一样
   data = es.search(body=body, index=settings.ELASTICSEARCH_INDEX) 

python连接 elasticsearch 增加文档

es = Elasticsearch([{'host': settings.ELASTICSEARCH_HOST, 'port': settings.ELASTICSEARCH_PORT}],
                           timeout=3600)
action = {
    "type_id": now_ameme_data.get("type_id"),
    "video_comment": now_ameme_data.get("video_comment"),
    "share_count": now_ameme_data.get("share_count"),
    "video_url": now_ameme_data.get("video_url"),
    "category_id": now_ameme_data.get("category_id"),
    "video_title": now_ameme_data.get("video_title"),
    "user_id": now_ameme_data.get("user_id"),
    "price": now_ameme_data.get("price"),
    "video_like": now_ameme_data.get("video_like"),
    "video_date": now_ameme_data.get("video_date"),
    "updata_time": now_ameme_data.get("update_time"),
    "video_img_url": now_ameme_data.get("video_img_url"),
    "label": label
}
es.index(index="aweme_smart", body=action, id=aweme_id)

新增文档使用的是 index 方法,也可以为文档指定 id。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值