用Python客户端开始的“Elasticsearch初学者指南”

概述

这是一个总结了从安装Elasticsearch到运用的准备工作的备忘录。我们将使用Python客户端来操作。有了这个工具,可以通过Python来添加和搜索数据,因此数据处理也会变得更加轻松……我认为。

设置环境

安装 Elasticsearch

由于环境是Debian,所以带着deb的软件包来进行安装。

% wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.3.1.deb
% sudo dpkg -i elasticsearch-1.3.1.deb

将我的 JAVA_HOME 路径(/usr/loca/java)加入到用于寻找 /etc/init.d/elasticsearch 中的java的目录中。

# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/local/java /usr/lib/jvm/java-7-oracle /usr/lib/jvm/java-7-openjdk /usr/lib/jvm/java-7-openjdk-amd64/ /usr/lib/jvm/java-7-openjdk-armhf /usr/lib/jvm/java-7-openjdk-i386/ /usr/lib/jvm/default-java"

启动

% sudo /etc/init.d/elasticsearch start

确认

请尝试访问 http://localhost:9200 并确认返回以下内容。
您可以通过浏览器访问地址并确认,或者通过命令行以以下方式进行访问。

% curl -XGET http://localhost:9200/                                                       
{
  "status" : 200,
  "name" : "White Rabbit",
  "version" : {
    "number" : "1.3.1",
    "build_hash" : "2de6dc5268c32fb49b205233c138d93aaf772015",
    "build_timestamp" : "2014-07-28T14:45:15Z",
    "build_snapshot" : false,
    "lucene_version" : "4.9"
  },
  "tagline" : "You Know, for Search"
}

尝试使用插件

插件的安装

由於沒有什麼東西會讓人感到不方便,所以我會安裝常用的elasticsearch-head。這樣最基本的需求就可以滿足了。只需要執行elasticsearch附帶的plugin指令即可。太好了!

如果能够访问到 http://localhost:9200/_plugin/head ,那就表示成功。

% /usr/share/elasticsearch/bin/plugin -install mobz/elasticsearch-head
elasticsearch-head.png

使用Python客户端

公式: elasticsearch-py
文件:Python Elasticsearch 客户端

准备Python环境

我手上的计算机上装有 Python 2.6.6。由于我从未使用过 Python,因此我决定参考了一篇谷歌页面,来安装包管理器 pip 和用于切换环境的 virtualenv。

参考:不知不觉中,pip的安装变得容易了。

curl -kL https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
pip install virtualenv virtualenvwrapper
vi ~/.bashrc
# 下記の3行を追記
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/work
source /path/to/your/virtualenvwrapper.sh

安装 Python 客户端并进行交互性启动。

安装

pip install elasticsearch

启动

    • ターミナルで日本語通したいので,LANGを設定しつつpythonを対話モードで起動

 

    • elasticsearch を import

 

    elasticsearch のインスタンスを用意
% LANG=ja_JP.UTF8 python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from elasticsearch import Elasticsearch
>>> es = Elasticsearch("localhost:9200")
>>> es
<Elasticsearch([{'host': 'localhost', 'port': 9200}])>

向索引中添加文档

API:elasticsearch.Elasticsearch.index
API:elasticsearch模块的Elasticsearch对象的index方法

我們將添加以下類似的數據。索引(index)和文檔類型(doc_type)是必填項目。如果指定的索引不存在,則將創建新的索引。如果未指定ID,系統將自動分配一個。

    • index: fruit (必須項目)

 

    • doc_type: test (必須項目)

 

    • id: 1

 

    • body (必須項目)

name:apple, color:red

>>> es.index(index="fruit", doc_type="test", id=1, body={"name":"apple", "color":"red"})
{u'_type': u'test', u'_id': u'1', u'created': True, u'_version': 1, u'_index': u'fruit'}
elasticsearch-head-new-index.png
elasticsearch-new-index.png

尝试进行不同的操作

更改/新增

如果指定相同的ID,就会覆盖。

>>> es.index(index="fruit", doc_type="test", id=1, body={"name":"apple", "color":"green"})
{u'_type': u'test', u'_id': u'1', u'created': False, u'_version': 2, u'_index': u'fruit'}

如果没有指定id,将会随机分配。在下面的例子中,id为dnMiX8ufSiiZC_c8KwykuQ。

>>> es.index(index="fruit", doc_type="test", body={"name":"りんご", "color":"red"})
{u'_type': u'test', u'_id': u'dnMiX8ufSiiZC_c8KwykuQ', u'created': True, u'_version': 1, u'_index': u'fruit'}

获取数据

前提

以下是在索引”fruit”中设置了以下数据的状态。
文档类型已设置为”test”。

idnamecolor9qsreGQTTMSIsMzlEe0H0Aりんごred3MH8LiCNSkOgZMwx_kNebwappleredYXAo8TfrQbeF3JQpW6dakwbananayellowmz1wlxRUSSWvCuIIh6k4OQorangeorangeMBEGluC5S-OzNdGoDYavGgapplegreen

当id可以指定时

>>> res = es.get(index="fruit", doc_type="_all", id="MBEGluC5S-OzNdGoDYavGg")
>>> print json.dumps(res, indent=4)
{
    "_type": "test",
    "_source": {
        "color": "green",
        "name": "apple"
    },
    "_index": "fruit",
    "_version": 1,
    "found": true,
    "_id": "MBEGluC5S-OzNdGoDYavGg"
}

当需要指定查询条件时。

把全部带过来

>>> res = es.search(index="fruit", body={"query": {"match_all": {}}})
>>> print json.dumps(res, indent=4)
{
    "hits": {
        "hits": [
            {
                "_score": 1.0,
                "_type": "test",
                "_id": "3MH8LiCNSkOgZMwx_kNebw",
                "_source": {
                    "color": "red",
                    "name": "apple"
                },
                "_index": "fruit"
            },
            {
                "_score": 1.0,
                "_type": "test",
                "_id": "mz1wlxRUSSWvCuIIh6k4OQ",
                "_source": {
                    "color": "orange",
                    "name": "orange"
                },
                "_index": "fruit"
            },
            {
                "_score": 1.0,
                "_type": "test",
                "_id": "9qsreGQTTMSIsMzlEe0H0A",
                "_source": {
                    "color": "red",
                    "name": "\u308a\u3093\u3054"
                },
                "_index": "fruit"
            },
            {
                "_score": 1.0,
                "_type": "test",
                "_id": "MBEGluC5S-OzNdGoDYavGg",
                "_source": {
                    "color": "green",
                    "name": "apple"
                },
                "_index": "fruit"
            },
            {
                "_score": 1.0,
                "_type": "test",
                "_id": "YXAo8TfrQbeF3JQpW6dakw",
                "_source": {
                    "color": "yellow",
                    "name": "banana"
                },
                "_index": "fruit"
            }
        ],
        "total": 5,
        "max_score": 1.0
    },
    "_shards": {
        "successful": 5,
        "failed": 0,
        "total": 5
    },
    "took": 3,
    "timed_out": false
}

通过添加条件进行搜索

尝试搜索红色的物品。

>>> res = es.search(index="fruit", body={"query": {"match": {"color":"red"}}})
>>> print json.dumps(res, indent=2 , ensure_ascii=False)
{
  "hits": {
    "hits": [
      {
        "_score": 0.30685282000000003,
        "_type": "test",
        "_id": "3MH8LiCNSkOgZMwx_kNebw",
        "_source": {
          "color": "red",
          "name": "apple"
        },
        "_index": "fruit"
      },
      {
        "_score": 0.30685282000000003,
        "_type": "test",
        "_id": "9qsreGQTTMSIsMzlEe0H0A",
        "_source": {
          "color": "red",
          "name": "りんご"
        },
        "_index": "fruit"
      }
    ],
    "total": 2,
    "max_score": 0.30685282000000003
  },
  "_shards": {
    "successful": 5,
    "failed": 0,
    "total": 5
  },
  "took": 2,
  "timed_out": false
}

删除索引

水果索引完全消失了。

>>> es.indices.delete(index="fruit")
{u'acknowledged': True}
bannerAds