首页 > 编程 > Python > 正文

Python-ElasticSearch搜索查询的讲解

2020-02-16 01:22:04
字体:
来源:转载
供稿:网友

Elasticsearch 是一个开源的搜索引擎,建立在一个全文搜索引擎库 Apache Lucene™ 基础之上。 Lucene 可能是目前存在的,不论开源还是私有的,拥有最先进,高性能和全功能搜索引擎功能的库。但是 Lucene 仅仅只是一个库。为了利用它,你需要编写 Java 程序,并在你的 java 程序里面直接集成 Lucene 包。 更坏的情况是,你需要对信息检索有一定程度的理解才能明白 Lucene 是怎么工作的。Lucene 是 很 复杂的。

在上一篇文章中介绍了ElasticSearch的简单使用,接下来记录一下ElasticSearch的查询:

查询所有数据

# 搜索所有数据es.search(index="my_index",doc_type="test_type")# 或者body = {  "query":{    "match_all":{}  }}es.search(index="my_index",doc_type="test_type",body=body)

term与terms

# termbody = {  "query":{    "term":{      "name":"python"    }  }}# 查询name="python"的所有数据es.search(index="my_index",doc_type="test_type",body=body)# termsbody = {  "query":{    "terms":{      "name":[        "python","android"      ]    }  }}# 搜索出name="python"或name="android"的所有数据es.search(index="my_index",doc_type="test_type",body=body)

match与multi_match

# match:匹配name包含python关键字的数据body = {  "query":{    "match":{      "name":"python"    }  }}# 查询name包含python关键字的数据es.search(index="my_index",doc_type="test_type",body=body)# multi_match:在name和addr里匹配包含深圳关键字的数据body = {  "query":{    "multi_match":{      "query":"深圳",      "fields":["name","addr"]    }  }}# 查询name和addr包含"深圳"关键字的数据es.search(index="my_index",doc_type="test_type",body=body)

ids

body = {  "query":{    "ids":{      "type":"test_type",      "values":[        "1","2"      ]    }  }}# 搜索出id为1或2d的所有数据es.search(index="my_index",doc_type="test_type",body=body)

复合查询bool

bool有3类查询关系,must(都满足),should(其中一个满足),must_not(都不满足)

body = {  "query":{    "bool":{      "must":[        {          "term":{            "name":"python"          }        },        {          "term":{            "age":18          }        }      ]    }  }}# 获取name="python"并且age=18的所有数据es.search(index="my_index",doc_type="test_type",body=body)

切片式查询

body = {  "query":{    "match_all":{}  }  "from":2  # 从第二条数据开始  "size":4  # 获取4条数据}# 从第2条数据开始,获取4条数据es.search(index="my_index",doc_type="test_type",body=body)

范围查询

body = {  "query":{    "range":{      "age":{        "gte":18,    # >=18        "lte":30    # <=30      }    }  }}# 查询18<=age<=30的所有数据es.search(index="my_index",doc_type="test_type",body=body)            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表