案例来自https://www.cnblogs.com/qdhxhz/p/11493677.html
一、准备数据
1、定义Index
PUT student
{
"settings":{
"number_of_shards":1,
"number_of_replicas":1
},
"mappings":{
"properties":{
"name":{"type":"text"},
"address":{"type":"keyword"},
"age":{"type":"integer"},
"interests":{"type":"text"},
"birthday":{"type":"date"}
}
}
}
2、添加测试数据
POST /student/_doc/1
{
"name":"徐小小",
"address":"杭州",
"age":3,
"interests":"唱歌 画画 跳舞",
"birthday":"2017-06-19"
}
POST /student/_doc/2
{
"name":"刘德华",
"address":"香港",
"age":28,
"interests":"演戏 旅游",
"birthday":"1980-06-19"
}
POST /student/_doc/3
{
"name":"张小斐",
"address":"北京",
"age":28,
"interests":"小品 旅游",
"birthday":"1990-06-19"
}
POST /student/_doc/4
{
"name":"王小宝",
"address":"德州",
"age":63,
"interests":"演戏 小品 打牌",
"birthday":"1956-06-19"
}
POST /student/_doc/5
{
"name":"向华强",
"address":"香港",
"age":31,
"interests":"演戏 主持",
"birthday":"1958-06-19"
}
获取数据总数:
![](https://img.haomeiwen.com/i7007629/43298cad146bd3f5.png)
二、Query查询
2.1、match查询
#1、 查询年龄为3的(命中:ID = 1)
GET student/_search
{
"query":{
"match":{"age": 3}
}
}
#2、查询兴趣里包含'演戏'的 (命中 ID = 2,5,4)
GET student/_search
{
"query":{
"match":{"interests": "演戏"}
}
}
#这里只要interests包含'演戏','演','戏'的都会命中
#3、查询索引所有文档 (命中 ID = 1,2,3,4,5)
GET student/_search
{
"query":{
"match_all": {}
}
}
#4、查询name或者address包含'德' (命中 ID = 2)
GET student/_search
{
"query":{
"multi_match": {
"query": "德",
"fields":["name","address"]
}
}
}
#说明 这里文档ID为4的address为'德州',应该也包含'德',但却没有被命中,原因是我们索引结构中,address属性是一个keyword类型,它是需要完全匹配,而不是包含的关系。name字段是text类型,包含关系即可
#如果这里query为'德州'就可以命中2条数据。
#5、查询兴趣里包含'演员'的 (命中 无)
GET student/_search
{
"query":{
"match_phrase":{"interests": "演员"}
}
}
# 这里和match的区别是这里是真正包含'演员',而不是只要满足其中一个字就会被模糊命中
![](https://img.haomeiwen.com/i7007629/7a3f7ad7d076ddb2.png)
![](https://img.haomeiwen.com/i7007629/83db4473d076716d.png)
2.2、term查询和terms查询
这种查询适合keyword 、numeric、date
![](https://img.haomeiwen.com/i7007629/af1a397e02d20dd9.png)
yay@yay-ThinkPad-T470-W10DG:~$ curl -H "Content-Type: application/json" -XPOST http://localhost:9200/student/_doc/_search?pretty -d '{
"query":{
"term":{
"address":"香港"
}
}
}'
![](https://img.haomeiwen.com/i7007629/270250fad30b9f14.png)
![](https://img.haomeiwen.com/i7007629/b40ec0083c1abbf4.png)
#2、查询地址等于"香港"或"北京"的 (命中: ID =2,3,5)
GET student/_search
{
"query":{
"terms":{
"address":["香港","北京"]
}
}
}
![](https://img.haomeiwen.com/i7007629/4d1ccaef87004cc1.png)
![](https://img.haomeiwen.com/i7007629/ec7172b76e34fb8e.png)
三、Filter查询
#1、获取年龄为3的 (命中 ID = 1)
GET student/_search
{
"post_filter":{
"term":{"age": 3}
}
}
#2、查询年纪为3或者63的 (命中 ID = 1,4)
GET student/_search
{
"post_filter":{
"terms":{"age":[3,63]}
}
}
网友评论