Elasticsearch上手——Python API的简单使用

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
云数据库 MongoDB,通用型 2核4GB
简介: Python够直接,从它开始是个不错的选择。Elasticsearch客户端列表:https://www.elastic.co/guide/en/elasticsearch/client/index.

Python够直接,从它开始是个不错的选择。

Elasticsearch客户端列表:https://www.elastic.co/guide/en/elasticsearch/client/index.html
Python API:https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/index.html
参考文档:http://elasticsearch-py.readthedocs.io/en/master/index.html

安装

我在CentOS 7上安装了Python3.6,安装时使用下面的命令:

pip3 install elasticsearch

安装时需要root权限

牛刀小试

由于Elasticsearch索引的文档是JSON形式,而MongoDB存储也是以JSON形式,因此这里选择通过MongoDB导出数据添加到Elasticsearch中。

使用MongoDB的Python API时,需要先安装pymongo,命令:pip3 install pymongo

import traceback
from pymongo import MongoClient
from elasticsearch import Elasticsearch

# 建立到MongoDB的连接
_db = MongoClient('mongodb://127.0.0.1:27017')['blog']

# 建立到Elasticsearch的连接
_es = Elasticsearch()

# 初始化索引的Mappings设置
_index_mappings = {
  "mappings": {
    "user": { 
      "properties": { 
        "title":    { "type": "text"  }, 
        "name":     { "type": "text"  }, 
        "age":      { "type": "integer" }  
      }
    },
    "blogpost": { 
      "properties": { 
        "title":    { "type": "text"  }, 
        "body":     { "type": "text"  }, 
        "user_id":  {
          "type":   "keyword" 
        },
        "created":  {
          "type":   "date"
        }
      }
    }
  }
}

# 如果索引不存在,则创建索引
if _es.indices.exists(index='blog_index') is not True:
  _es.indices.create(index='blog_index', body=_index_mappings) 

# 从MongoDB中查询数据,由于在Elasticsearch使用自动生成_id,因此从MongoDB查询
# 返回的结果中将_id去掉。
user_cursor = db.user.find({}, projection={'_id':False})
user_docs = [x for x in user_cursor]

# 记录处理的文档数
processed = 0
# 将查询出的文档添加到Elasticsearch中
for _doc in user_docs:
  try:
    # 将refresh设为true,使得添加的文档可以立即搜索到;
    # 默认为false,可能会导致下面的search没有结果
    _es.index(index='blog_index', doc_type='user', refresh=True, body=_doc)
    processed += 1
    print('Processed: ' + str(processed), flush=True)
  except:
    traceback.print_exc()

# 查询所有记录结果
print('Search all...',  flush=True)
_query_all = {
  'query': {
    'match_all': {}
  }
}
_searched = _es.search(index='blog_index', doc_type='user', body=_query_all)
print(_searched, flush=True)

# 输出查询到的结果
for hit in _searched['hits']['hits']:
  print(hit['_source'], flush=True)

# 查询姓名中包含jerry的记录
print('Search name contains jerry.', flush=True)
_query_name_contains = {
  'query': {
    'match': {
      'name': 'jerry'
    }
  }
}
_searched = _es.search(index='blog_index', doc_type='user', body=_query_name_contains)
print(_searched, flush=True)

运行上面的文件(elasticsearch_trial.py):

python3 elasticsearch_tria.py

可以得到下面的输出结果:

Processed: 1
Processed: 2
Processed: 3
Search all...
{'took': 1, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'failed': 0}, 'hits': {'total': 3, 'max_score': 1.0, 'hits': [{'_index': 'blog_index', '_type': 'user', '_id': 'AVn4TrrVXvwnWPWhxu5q', '_score': 1.0, '_source': {'title': 'Manager', 'name': 'Trump Heat', 'age': 67}}, {'_index': 'blog_index', '_type': 'user', '_id': 'AVn4TrscXvwnWPWhxu5s', '_score': 1.0, '_source': {'title': 'Engineer', 'name': 'Tommy Hsu', 'age': 32}}, {'_index': 'blog_index', '_type': 'user', '_id': 'AVn4Trr2XvwnWPWhxu5r', '_score': 1.0, '_source': {'title': 'President', 'name': 'Jerry Jim', 'age': 21}}]}}
{'title': 'Manager', 'name': 'Trump Heat', 'age': 67}
{'title': 'Engineer', 'name': 'Tommy Hsu', 'age': 32}
{'title': 'President', 'name': 'Jerry Jim', 'age': 21}
Search name contains jerry.
{'took': 3, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'failed': 0}, 'hits': {'total': 1, 'max_score': 0.25811607, 'hits': [{'_index': 'blog_index', '_type': 'user', '_id': 'AVn4Trr2XvwnWPWhxu5r', '_score': 0.25811607, '_source': {'title': 'President', 'name': 'Jerry Jim', 'age': 21}}]}}

这里写图片描述

相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
目录
相关文章
|
1天前
|
缓存 监控 API
利用Python构建高性能的Web API后端服务
随着微服务架构的普及和RESTful API的广泛应用,构建高性能、可扩展的Web API后端服务变得尤为重要。本文将探讨如何利用Python这一强大且灵活的语言,结合现代Web框架和工具,构建高效、可靠的Web API后端服务。我们将分析Python在Web开发中的优势,介绍常用的Web框架,并通过实际案例展示如何设计并实现高性能的API服务。
|
4天前
|
存储 缓存 监控
利用Python和Flask构建RESTful API的实战指南
在当今的软件开发中,RESTful API已成为前后端分离架构中的核心组件。本文将带你走进实战,通过Python的Flask框架,一步步构建出高效、安全的RESTful API。我们将从项目初始化、路由设置、数据验证、错误处理到API文档生成,全方位地探讨如何构建RESTful API,并给出一些实用的最佳实践和优化建议。
|
4天前
|
Web App开发 JavaScript 测试技术
python自动化测试实战 —— WebDriver API的使用
python自动化测试实战 —— WebDriver API的使用
8 1
|
4天前
|
API 数据安全/隐私保护 开发者
用 Python 优雅地玩转 Elasticsearch:实用技巧与最佳实践
用 Python 优雅地玩转 Elasticsearch:实用技巧与最佳实践
24 6
|
4天前
|
存储 自然语言处理 搜索推荐
Elasticsearch 8.10 同义词管理新篇章:引入同义词 API
Elasticsearch 8.10 同义词管理新篇章:引入同义词 API
15 0
|
4天前
|
存储 数据可视化 数据建模
阿里云大佬叮嘱我务必要科普这个 Elasticsearch API
阿里云大佬叮嘱我务必要科普这个 Elasticsearch API
15 0
|
4天前
|
机器学习/深度学习 算法 数据挖掘
机器学习--K近邻算法,以及python中通过Scikit-learn库实现K近邻算法API使用技巧
机器学习--K近邻算法,以及python中通过Scikit-learn库实现K近邻算法API使用技巧
|
4天前
|
缓存 前端开发 API
toapi,一个强大的 Python Web API库!
toapi,一个强大的 Python Web API库!
29 5
|
4天前
|
API Python
[AIGC] Python列表([])和字典({})常用API介绍
[AIGC] Python列表([])和字典({})常用API介绍
|
开发框架 jenkins 持续交付
跨平台API对接(Python)的使用
跨平台API对接(Python)的使用

热门文章

最新文章