python基础--Mac下Elasticsearch的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013210620/article/details/81286478

环境配置

环境依赖:
操作系统:Mac
  Python:3.6.5
  ElasticSearch:5.6.9 
  Java:1.8
  elasticdump
  elasticsearch-analysis-ik 6.3.2
  

安装elasticsearch

通过pip install elasticsearch进行安装
或者通过brew install [email protected]安装

配置elasticsearch环境变量


admindeMBP:lab admin$ echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.bash_profile

admindeMBP:lab admin$ ls /usr/local/opt/elasticsearch@5.6/bin

elasticsearch       elasticsearch-keystore  elasticsearch-plugin    elasticsearch-translog

配置好path变量,进行查看

zhiliaodeMBP:~ zhiliao$ which elasticsearch
/usr/local/opt/elasticsearch@5.6/bin/elasticsearch
zhiliaodeMBP:~ zhiliao$ 

安装Java SDK

由于elasticsearch是利用Java进行开发的,所以我们还需要安装Java环境
官网:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
版本:jdk1.8

安装分词器

参考https://github.com/medcl/elasticsearch-analysis-ik
首先通过which elasticsearch-plugin查看是否安装plugin

zhiliaodeMBP:~ zhiliao$ which elasticsearch-plugin
/usr/local/opt/elasticsearch@5.6/bin/elasticsearch-plugin

我本机已经安装,然后就去安装elasticsearch-analysis-ik分词器
目前官方最新版本是v6.3.2
然后就下载即可,通过如下命令

elasticsearch-plugin  install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.6.9/elasticsearch-analysis-ik-5.6.9.zip

安装elasticdump数据迁移

通过npm install -g elasticdump进行安装
然后通过如下命令查看是否安装,我本机已经安装

zhiliaodeMBP:~ zhiliao$ which elasticdump
/usr/local/bin/elasticdump

测试运行

如果一切正常,Elastic 就会在默认的9200端口运行。这时,打开另一个命令行窗口,请求该端口,会得到说明信息。

zhiliaodeMBP:~ zhiliao$ curl localhost:9200
{
  "name" : "hOWqTfH",
  "cluster_name" : "elasticsearch_zhiliao",
  "cluster_uuid" : "hWBc33irTL-wCsEbnLTjgw",
  "version" : {
    "number" : "5.6.9",
    "build_hash" : "877a590",
    "build_date" : "2018-04-12T16:25:14.838Z",
    "build_snapshot" : false,
    "lucene_version" : "6.6.1"
  },
  "tagline" : "You Know, for Search"
}

上面代码中,请求9200端口,Elastic 返回一个 JSON 对象,包含当前节点、集群、版本等信息。

名词概念、查看index、查看type

Cluster

Elastic 本质上是一个分布式数据库,允许多台服务器协同工作,每台服务器可以运行多个 Elastic 实例。

单个 Elastic 实例称为一个节点(node)。一组节点构成一个集群(cluster)。

Index
Elastic 会索引所有字段,经过处理后写入一个反向索引(Inverted Index)。查找数据的时候,直接查找该索引。

所以,Elastic 数据管理的顶层单位就叫做 Index(索引)。它是单个数据库的同义词。每个 Index (即数据库)的名字必须是小写。
下面的命令可以查看当前节点的所有 Index。

zhiliaodeMBP:~ zhiliao$ curl -X GET 'http://localhost:9200/_cat/indices?v'
health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   question   E6iJvA5RTpq1LnJQr748dQ   5   1      66974         8169     41.9mb         41.9mb
yellow open   index_2    pgyxlcW9QHORddZeLNGeDg   5   1          2            0      8.1kb          8.1kb
yellow open   my-index   wNnhnRtNTkaVziWKU_7_mA   5   1          0            0       839b           839b
yellow open   qa         v6avnFsfSResWMs0LcAXdQ   5   1          8            0     66.7kb         66.7kb
yellow open   qrelations pemnB8e-SumcYVNQRyYNAA   5   1      88736         6301     14.3mb         14.3mb
yellow open   index_1    mM3Mu8f0RGevilONzlQ4ew   5   1          1            0      4.4kb          4.4kb

Document
Index 里面单条的记录称为 Document(文档)。许多条 Document 构成了一个 Index。
同一个 Index 里面的 Document,不要求有相同的结构(scheme),但是最好保持相同,这样有利于提高搜索效率。

Type
Document 可以分组,比如weather这个 Index 里面,可以按城市分组(北京和上海),也可以按气候分组(晴天和雨天)。这种分组就叫做 Type,它是虚拟的逻辑分组,用来过滤 Document。

不同的 Type 应该有相似的结构(schema),举例来说,id字段不能在这个组是字符串,在另一个组是数值。这是与关系型数据库的表的一个区别。性质完全不同的数据(比如products和logs)应该存成两个 Index,而不是一个 Index 里面的两个 Type(虽然可以做到)。

这里我只列出了某一个index的数据
以如下的index_1 为例

es.index(index="index_1", doc_type="index_1", id=1, body={"any": "index_1_1_data", "age": 30})
es.index(index="index_1", doc_type="index_2", id=2, body={"any": "index_1_2_data", "age": 40})

下面的命令可以列出每个 Index 所包含的 Type。
curl 'localhost:9200/_mapping?pretty=true'

{
    "index_1":{
        "mappings":{
            "index_2":{
                "properties":{
                    "age":{ "type":"long" },
                    "any":{ "type":"text", "fields":{ "keyword":{ "type":"keyword", "ignore_above":256 } } } }
            },
            "index_1":{
                "properties":{
                    "age":{ "type":"long" },
                    "any":{ "type":"text", "fields":{ "keyword":{ "type":"keyword", "ignore_above":256 } } } }
            }
        }
    }
}

新建、删除index

首先列出当前的index

zhiliaodeMBP:~ zhiliao$ curl -X GET 'http://localhost:9200/_cat/indices?v'
health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   question   E6iJvA5RTpq1LnJQr748dQ   5   1      66974         8169     41.9mb         41.9mb
yellow open   index_2    pgyxlcW9QHORddZeLNGeDg   5   1          2            0      8.1kb          8.1kb
yellow open   my-index   wNnhnRtNTkaVziWKU_7_mA   5   1          0            0       839b           839b
yellow open   index_1    np0ouRCDRC-eXDrilpSFjQ   5   1          3            0     11.7kb         11.7kb
yellow open   qa         v6avnFsfSResWMs0LcAXdQ   5   1          8            0     66.7kb         66.7kb
yellow open   qrelations pemnB8e-SumcYVNQRyYNAA   5   1      88736         6301     14.3mb         14.3mb

新建index

新建 Index,可以直接向 Elastic 服务器发出 PUT 请求。下面的例子是新建一个名叫weather的 Index。
curl -X PUT 'localhost:9200/weather'

zhiliaodeMBP:~ zhiliao$ curl -X PUT 'localhost:9200/weather'
{"acknowledged":true,"shards_acknowledged":true,"index":"weather"}zhiliaodeMBP:~ zhiliao$ 

在次列举出所有的index

zhiliaodeMBP:~ zhiliao$ curl -X GET 'http://localhost:9200/_cat/indices?v'
health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   weather    8xNoUnPhReyihkPgxQZtzw   5   1          0            0       324b           324b
yellow open   index_1    np0ouRCDRC-eXDrilpSFjQ   5   1          3            0     11.7kb         11.7kb
yellow open   qrelations pemnB8e-SumcYVNQRyYNAA   5   1      88736         6301     14.3mb         14.3mb
yellow open   qa         v6avnFsfSResWMs0LcAXdQ   5   1          8            0     66.7kb         66.7kb
yellow open   question   E6iJvA5RTpq1LnJQr748dQ   5   1      66974         8169     41.9mb         41.9mb
yellow open   index_2    pgyxlcW9QHORddZeLNGeDg   5   1          2            0      8.1kb          8.1kb
yellow open   my-index   wNnhnRtNTkaVziWKU_7_mA   5   1          0            0       839b           839b

我们发现增加了weather的index

我们看下新建的weather索引的数据格式,如下是新建的weather索引的数据格式

"weather":{
        "mappings":{

        }
    }

删除index

然后我们通过然后,我们发出 DELETE 请求,删除这个 Index
curl -X DELETE 'localhost:9200/weather'

zhiliaodeMBP:~ zhiliao$ curl -X DELETE 'localhost:9200/weather'
{"acknowledged":true}zhiliaod-X GET 'http://localhost:9200/_cat/indices?v'
health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   question   E6iJvA5RTpq1LnJQr748dQ   5   1      66974         8169     41.9mb         41.9mb
yellow open   index_2    pgyxlcW9QHORddZeLNGeDg   5   1          2            0      8.1kb          8.1kb
yellow open   my-index   wNnhnRtNTkaVziWKU_7_mA   5   1          0            0       839b           839b
yellow open   index_1    np0ouRCDRC-eXDrilpSFjQ   5   1          3            0     11.7kb         11.7kb
yellow open   qrelations pemnB8e-SumcYVNQRyYNAA   5   1      88736         6301     14.3mb         14.3mb
yellow open   qa         v6avnFsfSResWMs0LcAXdQ   5   1          8            0     66.7kb         66.7kb
zhiliaodeMBP:~ zhiliao$ 

我们在次列出所有的index就发现已经没有之前的weather的索引了

中文分词设置

创建含有分词的index

在本文第一部分已经介绍了如何安装分词器就,现在我们就来新建一个 Index,指定需要分词的字段

curl -X PUT 'localhost:9200/index_safly' -d '
> {
>   "mappings": {
>     "person": {
>       "properties": {
>         "user": {
>           "type": "text",
>           "analyzer": "ik_max_word",
>           "search_analyzer": "ik_max_word"
>         },
>         "title": {
>           "type": "text",
>           "analyzer": "ik_max_word",
>           "search_analyzer": "ik_max_word"
>         },
>         "desc": {
>           "type": "text",
>           "analyzer": "ik_max_word",
>           "search_analyzer": "ik_max_word"
>         }
>       }
>     }
>   }
> }'

按下回车键执行上述操作后,会输出如下的返回结果,索引创建成功

{"acknowledged":true,"shards_acknowledged":true,"index":"index_safly"}

上面代码中,首先新建一个名称为index_safly的 Index,里面有一个名称为person的 Type。person有三个字段user、title、desc

这三个字段都是中文,而且类型都是文本(text),所以需要指定中文分词器,不能使用默认的英文分词器。

Elastic 的分词器称为 analyzer。我们对每个字段指定分词器。

上面代码中,analyzer是字段文本的分词器,search_analyzer是搜索词的分词器。ik_max_word分词器是插件ik提供的,可以对文本进行最大数量的分词。

数据操作

增加

在进行操作index_safly索引之前,我们先看看该索引的数据格式

{
    "index_safly":{
        "mappings":{
            "person":{
                "properties":{
                    "desc":{ "type":"text", "analyzer":"ik_max_word" },
                    "title":{ "type":"text", "analyzer":"ik_max_word" },
                    "user":{ "type":"text", "analyzer":"ik_max_word" } }
            }
        }
    }
}
新增记录/Index/Type(PUT方式)

向指定的 /Index/Type 发送 PUT 请求,就可以在 Index 里面新增一条记录。比如,向/index_safly/person发送请求,就可以新增一条人员记录。

curl -X PUT 'localhost:9200/index_safly/person/1' -d 
'{"user":"小王","title":"工程师","desc":"写代码的屌丝"}'

服务器返回的 JSON 对象,会给出 Index、Type、Id、Version 等信息。


{
    "_index":"index_safly",
    "_type":"person",
    "_id":"1",
    "_version":1,
    "result":"created",
    "_shards":{
        "total":2,
        "successful":1,
        "failed":0
    },
    "created":true
}
新增记录/Index/Type(POST方式)

如果你仔细看,会发现请求路径是/accounts/person/1,最后的1是该条记录的 Id。它不一定是数字,任意字符串(比如abc)都可以。
新增记录的时候,也可以不指定 Id,这时要改成 POST 请求。

curl -X POST 'localhost:9200/index_safly/person' -d 
'{"user":"小李","title":"工程师","desc":"写代码的屌丝"}'

上面代码中,向/accounts/person发出一个 POST 请求,添加一个记录。这时,服务器返回的 JSON 对象里面,_id字段就是一个随机字符串。

{
    "_index":"index_safly",
    "_type":"person",
    "_id":"AWTuZFsIPNA23LAXcpO7",
    "_version":1,
    "result":"created",
    "_shards":{
        "total":2,
        "successful":1,
        "failed":0
    },
    "created":true
}
一步生成index和记录

注意,如果没有先创建 Index(这个例子是accounts),直接执行上面的命令,Elastic 也不会报错,而是直接生成指定的 Index。所以,打字的时候要小心,不要写错 Index 的名称。我们看下执行结果

curl -X GET 'http://localhost:9200/_cat/indices?v'
health status index       uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   index_safly -l4j2UPpTgu64jsk7jzUvA   5   1          2            0      7.6kb          7.6kb
yellow open   index_1     np0ouRCDRC-eXDrilpSFjQ   5   1          3            0     11.7kb         11.7kb
yellow open   qrelations  pemnB8e-SumcYVNQRyYNAA   5   1      88736         6301     14.3mb         14.3mb
yellow open   qa          v6avnFsfSResWMs0LcAXdQ   5   1          8            0     66.7kb         66.7kb
yellow open   question    E6iJvA5RTpq1LnJQr748dQ   5   1      66974         8169     41.9mb         41.9mb
yellow open   index_2     pgyxlcW9QHORddZeLNGeDg   5   1          2            0      8.1kb          8.1kb
yellow open   my-index    wNnhnRtNTkaVziWKU_7_mA   5   1          0            0       839b           839b
zhiliaodeMBP:~ zhiliao$ 
zhiliaodeMBP:~ zhiliao$ 
zhiliaodeMBP:~ zhiliao$ curl -X POST 'localhost:9200/index_temp/person' -d '{"user":"小李","title":"工程师","desc":"写代码的屌丝"}'
{"_index":"index_temp","_type":"person","_id":"AWTuZjKXPNA23LAXcpO9","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"created":true}zhiliaodeMBP:~ zhiliao$ 
zhiliaodeMBP:~ zhiliao$ 
zhiliaodeMBP:~ zhiliao$ curl -X GET 'http://localhost:9200/_cat/indices?v'
health status index       uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   index_safly -l4j2UPpTgu64jsk7jzUvA   5   1          2            0      7.6kb          7.6kb
yellow open   index_1     np0ouRCDRC-eXDrilpSFjQ   5   1          3            0     11.7kb         11.7kb
yellow open   index_temp  qS7IWYm-ROOFBjnNgVCE4w   5   1          1            0      5.2kb          5.2kb
yellow open   qrelations  pemnB8e-SumcYVNQRyYNAA   5   1      88736         6301     14.3mb         14.3mb
yellow open   qa          v6avnFsfSResWMs0LcAXdQ   5   1          8            0     66.7kb         66.7kb
yellow open   question    E6iJvA5RTpq1LnJQr748dQ   5   1      66974         8169     41.9mb         41.9mb
yellow open   index_2     pgyxlcW9QHORddZeLNGeDg   5   1          2            0      8.1kb          8.1kb
yellow open   my-index    wNnhnRtNTkaVziWKU_7_mA   5   1          0            0       839b           839b
zhiliaodeMBP:~ zhiliao$ 

最后我们看下生成的index_temp的数据格式

{
    "index_temp":{
        "mappings":{
            "person":{
                "properties":{
                    "desc":{ "type":"text", "fields":{ "keyword":{ "type":"keyword", "ignore_above":256 } } },
                    "title":{ "type":"text", "fields":{ "keyword":{ "type":"keyword", "ignore_above":256 } } },
                    "user":{ "type":"text", "fields":{ "keyword":{ "type":"keyword", "ignore_above":256 } } } }
            }
        }
    }
}

查看记录

向/Index/Type/Id发出 GET 请求,就可以查看这条记录。
通过curl 'localhost:9200/index_safly/person/1?pretty=true'
输出如下结果

{
  "_index" : "index_safly",
  "_type" : "person",
  "_id" : "1",
  "_version" : 1,
  "found" : true,
  "_source" : {
    "user" : "小王",
    "title" : "工程师",
    "desc" : "写代码的屌丝"
  }
}

上面代码请求查看/index_safly/person/1这条记录,URL 的参数pretty=true表示以易读的格式返回。

返回的数据中,found字段表示查询成功,_source字段返回原始记录。

如果 Id 不正确,就查不到数据,found字段就是false

zhiliaodeMBP:~ zhiliao$ curl 'localhost:9200/index_safly/person/12?pretty=true'
{
  "_index" : "index_safly",
  "_type" : "person",
  "_id" : "12",
  "found" : false
}

删除记录

删除记录就是发出 DELETE 请求。
通过命令curl -X DELETE 'localhost:9200/index_safly/person/AWTuZFsIPNA23LAXcpO7'删除那条我们随机生成ID的记录
返回如下结果:

{
    "found":true,
    "_index":"index_safly",
    "_type":"person",
    "_id":"AWTuZFsIPNA23LAXcpO7",
    "_version":2,
    "result":"deleted",
    "_shards":{
        "total":2,
        "successful":1,
        "failed":0
    }
}

更新记录

更新记录就是使用 PUT 请求,重新发送一次数据

curl -X PUT 'localhost:9200/index_safly/person/1' -d '
> {
>     "user" : "张三",
>     "title" : "工程师",
>     "desc" : "数据库管理,软件开发"
> }' 

然后返回如下的结果


{
    "_index":"index_safly",
    "_type":"person",
    "_id":"1",
    "_version":2,
    "result":"updated",
    "_shards":{
        "total":2,
        "successful":1,
        "failed":0
    },
    "created":false
}

可以看到,记录的 Id 没变,但是版本(version)从1变成2,操作类型(result)从created变成updated,created字段变成false,因为这次不是新建记录

我们在来查询下修改后的记录

curl 'localhost:9200/index_safly/person/1?pretty=true'
{
  "_index" : "index_safly",
  "_type" : "person",
  "_id" : "1",
  "_version" : 2,
  "found" : true,
  "_source" : {
    "user" : "张三",
    "title" : "工程师",
    "desc" : "数据库管理,软件开发"
  }
}

我们看到数据被修改了

数据查询

返回index下所有记录

使用 GET 方法,直接请求/Index/Type/_search,就会返回所有记录
使用curl 'localhost:9200/index_safly/person/_search'来查询该index下的 所有数据

{
    "took":1,
    "timed_out":false,
    "_shards":{
        "total":5,
        "successful":5,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":1,
        "max_score":1,
        "hits":[
            {
                "_index":"index_safly",
                "_type":"person",
                "_id":"1",
                "_score":1,
                "_source":{
                    "user":"张三",
                    "title":"工程师",
                    "desc":"数据库管理,软件开发"
                }
            }
        ]
    }
}

上面代码中,返回结果的 took字段表示该操作的耗时(单位为毫秒),timed_out字段表示是否超时,hits字段表示命中的记录,里面子字段的含义如下。
total:返回记录数,本例是2条。
max_score:最高的匹配程度,本例是1.0。
hits:返回的记录组成的数组。

全文检索

Elastic 的查询非常特别,使用自己的查询语法,要求 GET 请求带有数据体。

curl 'localhost:9200/index_safly/person/_search' -d '
> {
>   "query" : { "match" : { "desc" : "软件" }}
> }'

上面代码使用 Match 查询,指定的匹配条件是desc字段里面包含”软件”这个词。返回结果如下,查询结果如下:

{
    "took":4,
    "timed_out":false,
    "_shards":{
        "total":5,
        "successful":5,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":1,
        "max_score":0.28582606,
        "hits":[
            {
                "_index":"index_safly",
                "_type":"person",
                "_id":"1",
                "_score":0.28582606,
                "_source":{
                    "user":"张三",
                    "title":"工程师",
                    "desc":"数据库管理,软件开发"
                }
            }
        ]
    }
}

如果查询不到就返回如下的结果:


{
    "took":1,
    "timed_out":false,
    "_shards":{
        "total":5,
        "successful":5,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":0,
        "max_score":null,
        "hits":[

        ]
    }
}

Elastic 默认一次返回10条结果,可以通过size字段改变这个设置。

curl 'localhost:9200/index_safly/person/_search' -d '
{
  "query" : { "match" : { "desc" : "软件" }},"size":1
}'

还可以通过from字段,指定位移。

curl 'localhost:9200/index_safly/person/_search' -d '
{
  "query" : { "match" : { "desc" : "软件" }},"from":1,"size":1
}'

逻辑运算

or

如果有多个搜索关键字, Elastic 认为它们是or关系

curl 'localhost:9200/index_safly/person/_search' -d '
{
  "query" : { "match" : { "desc" : "软件 管理" }}                  
}'

查询结果如下,没有变化

{
    "took":10,
    "timed_out":false,
    "_shards":{
        "total":5,
        "successful":5,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":1,
        "max_score":0.5716521,
        "hits":[
            {
                "_index":"index_safly",
                "_type":"person",
                "_id":"1",
                "_score":0.5716521,
                "_source":{
                    "user":"张三",
                    "title":"工程师",
                    "desc":"数据库管理,软件开发"
                }
            }
        ]
    }
}

and

如果要执行多个关键词的and搜索,必须使用布尔查询。

 curl 'localhost:9200/index_safly/person/_search'  -d '
{
  "query": {
    "bool": {
      "must": [
        { "match": { "desc": "软件" } },
        { "match": { "desc": "管理" } }
      ]
    }
  }
}'

输出结果如下:

{
    "took":5,
    "timed_out":false,
    "_shards":{
        "total":5,
        "successful":5,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":1,
        "max_score":0.5716521,
        "hits":[
            {
                "_index":"index_safly",
                "_type":"person",
                "_id":"1",
                "_score":0.5716521,
                "_source":{
                    "user":"张三",
                    "title":"工程师",
                    "desc":"数据库管理,软件开发"
                }
            }
        ]
    }
}

如果不能匹配,如下的检索条件

 curl 'localhost:9200/index_safly/person/_search'  -d '
{
  "query": {
    "bool": {
      "must": [
        { "match": { "desc": "软件" } },
        { "match": { "desc": "系统" } }
      ]
    }
  }
}'

就会输出如下的错误

{
    "took":2,
    "timed_out":false,
    "_shards":{
        "total":5,
        "successful":5,
        "skipped":0,
        "failed":0
    },
    "hits":{
        "total":0,
        "max_score":null,
        "hits":[

        ]
    }
}

其他

index增加、get查询

from elasticsearch import Elasticsearch

es = Elasticsearch(['localhost:9200'])

############index增加############
es.index(index="index_1", doc_type="index_1", id=1, body={"any": "index_1_1_data", "age": 30})
es.index(index="index_1", doc_type="index_1", id=2, body={"any": "index_1_2_data", "age": 40})

es.index(index="index_2", doc_type="index_2", id=1, body={"any": "index_2_1_data", "age": 30})
es.index(index="index_2", doc_type="index_2", id=2, body={"any": "index_2_2_data", "age": 40})

#############get查询############

ret = es.get(index='index_1', doc_type='index_1', id=1)
print(ret)

#############更新字段############
es.update(index='index_1', doc_type='index_1', id=1, body={"doc": {"any": 'jackaaa'}})
ret = es.get(index='index_1', doc_type='index_1', id=1)
print(ret)

#############添加字段############
es.update(index='index_1', doc_type='index_1', id=1, body={'script': "ctx._source.address = '合肥'"})
ret = es.get(index='index_1', doc_type='index_1', id=1)
print(ret)

#############删除字段############
es.update(index='index_1', doc_type='index_1', id=1, body={'script': "ctx._source.remove('address')"})
ret = es.get(index='index_1', doc_type='index_1', id=1)
print(ret)

输出结果如下:

{‘_source’: {‘any’: ‘index_1_1_data’, ‘age’: 30}, ‘_id’: ‘1’, ‘_index’: ‘index_1’, ‘_type’: ‘index_1’, ‘_version’: 12, ‘found’: True}

{‘_source’: {‘any’: ‘jackaaa’, ‘age’: 30}, ‘_id’: ‘1’, ‘_index’: ‘index_1’, ‘_type’: ‘index_1’, ‘_version’: 13, ‘found’: True}

{‘_source’: {‘address’: ‘合肥’, ‘any’: ‘jackaaa’, ‘age’: 30}, ‘_id’: ‘1’, ‘_index’: ‘index_1’, ‘_type’: ‘index_1’, ‘_version’: 14, ‘found’: True}

{‘_source’: {‘any’: ‘jackaaa’, ‘age’: 30}, ‘_id’: ‘1’, ‘_index’: ‘index_1’, ‘_type’: ‘index_1’, ‘_version’: 15, ‘found’: True}

通过log日志看到,输出的4条分别是 get查询、更新字段后、添加字段后,删除字段后的输出结果

es.index(index="index_1", doc_type="index_1", id=1, body={"any": "index_1_1_data", "age": 30})
es.index(index="index_1", doc_type="index_1", id=2, body={"any": "index_1_2_data", "age": 40})

es.index(index="index_2", doc_type="index_2", id=1, body={"any": "index_2_1_data", "age": 30})
es.index(index="index_2", doc_type="index_2", id=2, body={"any": "index_2_2_data", "age": 40})

#查询所有的
ret = es.search(index="index_1", doc_type="index_1", body={'query': {'match_all': {}}})
print(ret)

#查询年龄打于35的
ret = es.search(index="index_1", doc_type="index_1", body={'query': {'range': {'age': {'gt': 35}}}})
print(ret)

结果如下:

{‘timed_out’: False, ‘_shards’: {‘successful’: 5, ‘failed’: 0, ‘total’: 5, ‘skipped’: 0}, ‘took’: 1, ‘hits’: {‘max_score’: 1.0, ‘total’: 2, ‘hits’: [{‘_index’: ‘index_1’, ‘_source’: {‘age’: 40, ‘any’: ‘index_1_2_data’}, ‘_score’: 1.0, ‘_id’: ‘2’, ‘_type’: ‘index_1’}, {‘_index’: ‘index_1’, ‘_source’: {‘age’: 30, ‘any’: ‘index_1_1_data’}, ‘_score’: 1.0, ‘_id’: ‘1’, ‘_type’: ‘index_1’}]}}

{‘timed_out’: False, ‘_shards’: {‘successful’: 5, ‘failed’: 0, ‘total’: 5, ‘skipped’: 0}, ‘took’: 1, ‘hits’: {‘max_score’: 1.0, ‘total’: 1, ‘hits’: [{‘_index’: ‘index_1’, ‘_source’: {‘age’: 40, ‘any’: ‘index_1_2_data’}, ‘_score’: 1.0, ‘_id’: ‘2’, ‘_type’: ‘index_1’}]}}

删除

from elasticsearch import Elasticsearch

es = Elasticsearch(['localhost:9200'])

############index增加############
es.index(index="index_1", doc_type="index_1", id=1, body={"any": "index_1_1_data", "age": 30})
es.index(index="index_1", doc_type="index_1", id=2, body={"any": "index_1_2_data", "age": 40})

es.index(index="index_2", doc_type="index_2", id=1, body={"any": "index_2_1_data", "age": 30})
es.index(index="index_2", doc_type="index_2", id=2, body={"any": "index_2_2_data", "age": 40})

es.delete(index="index_1",doc_type="index_1",id=1)
ret = es.search(index="index_1", doc_type="index_1", body={'query': {'match_all': {}}})
print(ret)

结果如下:
{‘_shards’: {‘failed’: 0, ‘successful’: 5, ‘total’: 5, ‘skipped’: 0}, ‘hits’: {‘hits’: [{‘_source’: {‘age’: 40, ‘any’: ‘index_1_2_data’}, ‘_index’: ‘index_1’, ‘_id’: ‘2’, ‘_score’: 1.0, ‘_type’: ‘index_1’}], ‘total’: 1, ‘max_score’: 1.0}, ‘timed_out’: False, ‘took’: 0}

猜你喜欢

转载自blog.csdn.net/u013210620/article/details/81286478