ElasticSearch可以执行复杂的条件查询,下面直接举例子:
首先先添加文档:
PUT /user_dao/user_table/1 { "name":"baby", "sex":0, "age":1 } PUT /user_dao/user_table/2 { "name":"father", "sex":0, "age":26 } PUT /user_dao/user_table/3 { "name":"mother", "sex":1, "age":24 } PUT /user_dao/user_table/4 { "name":"grandfather", "sex":1, "age":60 } PUT /user_dao/user_table/5 { "name":"grandmother", "sex":1, "age":58 }
1. 根据id进行查询
GET /user_dao/user_table/1
2.查询当前所有类型的文档
GET /user_dao/user_table/_search
3.根据多个ID批量查询 ,查询多个id分别为1、2
GET /user_dao/user_table/_mget { "ids":["1","2"] }
4.查询年龄为年龄24岁
GET /user_dao/user_table/_search?q=age:24
5. 查询年龄20岁-60岁之间(注意:TO 一定要大写)
GET /user_dao/user_table/_search?q=age[20 TO 60]
返回结果:
{ "took": 77, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 4, "max_score": 1, "hits": [ { "_index": "user_dao", "_type": "user_table", "_id": "5", "_score": 1, "_source": { "name": "grandmother", "sex": 1, "age": 58 } }, { "_index": "user_dao", "_type": "user_table", "_id": "2", "_score": 1, "_source": { "name": "father", "sex": 0, "age": 26 } }, { "_index": "user_dao", "_type": "user_table", "_id": "4", "_score": 1, "_source": { "name": "grandfather", "sex": 1, "age": 60 } }, { "_index": "user_dao", "_type": "user_table", "_id": "3", "_score": 1, "_source": { "name": "mother", "sex": 1, "age": 24 } } ] } }
6.查询年龄20岁-60岁之间并且年龄降序、从0条数据到第1条数据
GET /user_dao/user_table/_search?q=age[30 TO 60]&sort=age:desc&from=0&size=1
返回内容:
{ "took": 57, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 2, "max_score": null, "hits": [ { "_index": "user_dao", "_type": "user_table", "_id": "4", "_score": null, "_source": { "name": "grandfather", "sex": 1, "age": 60 }, "sort": [ 60 ] } ] } }
7.查询年龄20岁-60岁之间并且年龄降序、从0条数据到第1条数据,展示name和age字段
GET /user_dao/user_table/_search?q=age[30 TO 60]&sort=age:desc&from=0&size=1&_source=name,age
返回结果:
{ "took": 48, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 2, "max_score": null, "hits": [ { "_index": "user_dao", "_type": "user_table", "_id": "4", "_score": null, "_source": { "name": "grandfather", "age": 60 }, "sort": [ 60 ] } ] } }