Es-python常用查询语句示例

目录

ES-Python查询语句

1. 基本查询#

Copy
from elasticsearch import Elasticsearch

# 建立连接
es = Elasticsearch(
    hosts={'192.168.1.120', '192.168.1.123'},  # 地址
    timeout=3600  # 超时时间
)

#默认查询,没有任何筛选条件,默认显示前10条数据的所有信息
es.search(index='test')  # index:选择数据库

2. 过滤路径#

通过指定字段,只显示数据的指定字段信息(默认显示所有字段的信息)

Copy
#定义过滤字段,最终只显示此此段信息
filter_path=['hits.hits._source.ziduan1',  # 字段1
             'hits.hits._source.ziduan2']  # 字段2

es.search(index='test', filter_path=filter_path)  # 指定字段:filter_path

3. 切片查询#

通过制定body,进行条件查询. 类似于mysql中的WHERE.

Copy
# body指定查询条件
body = {
    'from': 0,  # 从0开始
    'size': 20
# 取20个数据。类似mysql中的limit 0, 20。 注:size可以在es.search中指定,也可以在此指定,默认是10
}

# 定义过滤字段,最终只显示此此段信息
filter_path=['hits.hits._source.ziduan1',  # 字段1
             'hits.hits._source.ziduan2']  # 字段2

es.search(index='test', filter_path=filter_path, body=body)  # 指定查询条件

4. 模糊查询match#

Copy
body = {
    'query': {  # 查询命令
        'match': {  # 查询方法:模糊查询(会被分词)。比如此代码,会查到只包含:“我爱你”, “中国”的内容
            'ziduan1': '我爱你中国'
        }
    },
  'size': 20  # 不指定默认是10,最大值不超过10000(可以修改,但是同时会增加数据库压力)
}

# size的另一种指定方法
es.search(index='test', filter_path=filter_path, body=body, size=200)  # 指定size,默认是10

5. 模糊查询match_phrase#

Copy
body = {
    'query': {  # 查询命令
        'match_phrase': {  # 查询方法:模糊查询(不会被分词)。会查到包含:“我爱你中国”的内容
            'ziduan1': '我爱你中国'
        }
    }
}

注:内容中的下划线等标点符号会被忽略,有与没有的效果一样

6. 精准单值查询term#

只能查询一个字段,且只能指定一个值. 类似于mysql中的 where ziduan='test'

Copy
body ={
    'query':{
        'term':{
            'ziduan1.keyword': '我爱你中国'  # 查询内容等于“我爱你中国的”的数据。查询中文,在字段后面需要加上.keyword
         # 'ziduan2': 'I love China'
        }
    }
}