注意事项:安装es的ik分词器可能导致es内存溢出,可以调整虚拟机内存到2G,es配置中增加内存限制:indices.fielddata.cache.size: 50%
GET /_cat/indices?v 查看索引数据
### 1.2 花式查询 >创建一个索引 ```json PUT /products/ { "mappings": { "properties": { "name":{ "type": "text", "analyzer": "ik_smart" }, "long_name":{ "type": "text", "brand_id":{ "type": "integer" }, "category_id":{ "type":"integer" }, "shop_id":{ "type":"integer" }, "price":{ "type":"scaled_float", "scaling_factor":100 }, "sold_count":{ "type":"integer" }, "review_count":{ "type":"integer" }, "status":{ "type":"integer" }, "create_time" : { "type" : "date" }, "last_time" : { "type" : "date" } } } }
GET /products/_search 返回结果: { "took" : 0, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "Failed" : 0 }, "hits" : { "total" : { "value" : 5, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "products", "_type" : "_doc", "_id" : "200039", "_score" : 1.0, "_source" : { "brand_id" : 1, "create_time" : "2021-05-21T00:00:00Z", "id" : 200039, "last_time" : "2021-05-21T00:00:00Z", "long_name" : "HUAWEi Mate Book 14 16G 512G ", "name" : "HUAWEi Mate Book 14", "price" : 9090, "review_count" : 11111, "shop_id" : 1, "sold_count" : 12345, "status" : 1, "three_category_id" : 3 } }, { "_index" : "products", "_id" : "200040", "id" : 200040, "long_name" : "HUAWEi Mate Book 13 16G 512G ", "name" : "HUAWEi Mate Book 13", "_id" : "200041", "id" : 200041, "name" : "IPhone Mate Book 13", "_id" : "200042", "id" : 200042, "long_name" : "OPPO 40s 16G 512G ", "name" : "OPPO 40s", "_id" : "200043", "id" : 200043, "long_name" : "MateBook 16G 512G ", "name" : "MateBook X", "three_category_id" : 3 } } ] } }
普通查询
如果是只想要查询name与price两个字段呢?
如何进行排序?默认是根据_score匹配分值进行降序排序的,但如果我们指定一个字段进行asc或者desc排序呢?这里我使用price来进行降序
在实际开发中,我们经常用到分页查询。那在elasticsearch中怎么做到分页呢?
以上就是一个es的分页查询,添加了from和size属性,其中from是指分页的起始索引,size是指分页容量
GET /products/_doc/_search { "query":{ "bool":{ "must":[ { "match":{ "name":"Book" } }, { "match":{ "shop_id":1 } } ] } } } 返回结果: { "took" : 80, "max_score" : 1.744874, "_score" : 1.744874, "price" : 8888, "price" : 5499,51); font-size: 15px; font-variant-numeric: normal; font-variant-east-asian: normal; margin-bottom: 16px; margin-top: 0px; white-space: normal;">其中bool代表此查询为布尔查询,也就是多条件查询,而must则是and的意思,就是后面集合里的所有条件都要满足:
must(and),所有的条件都要符合,相当于where id=1 and name=xxx
should(or),满足一个条件即可,相当于 where id=1 or name=xxx
must_not(!=),所有条件必须满足不等于,相当于where id!=1 and name!=xxx
GET /products/_doc/_search { "query":{ "bool":{ "should":[ { "match":{ "name":"Book" } }, { "match":{ "shop_id":1 } } ] } } } 返回结果: { "took" : 42, "hits" : { "total" : { "value" : 4, "price" : 13880,51); font-size: 15px; font-variant-numeric: normal; font-variant-east-asian: normal; margin-bottom: 16px; margin-top: 0px; white-space: normal;">must_not的查询
过滤查询