ES是一个分布式的restful风格的开源全文搜索和分析的引擎。可以实现PB级的数据搜索。在公司做的一个项目是根据相关的检索条件去搜索一些政府政策的文件。其中使用到了分页查询,排序,模糊检索和精准检索,以及多条件的查询。 (1)分页检索,可以通过size和from来实现,size返回的条数,默认是10条,from返回的开始。 { "from": 0, "size": 30, "sort": { "_score": { "order": "desc" } }, "query": { "bool": { "must": [ { "match": { "is_valid": true } }, { "range": { "publish_date": { "gte": "2019-06-11 00:00:00" } } } ] } } (2)排序,可以根据sort来实现,该字段可以指定索引字段,也可以指定返回结果中的其他字段。比如,这里是根据相关度来进行排序的,也可以指定publish_date--索引字段中的时间来排序。排序方式有desc和asc两种。 { "from": 0, "size": 30, "sort": { "_score": { "order": "desc" } }, "query": { "bool": { "must": [ { "match": { "is_valid": true } }, { "range": { "publish_date": { "gte": "2019-06-11 00:00:00" } } } ] } } (3)模糊查询和精准查询 模糊查询可以使用match,ES查询时会进行相关的分词操作。如: { "from": 0, "size": 30, "sort": { "_score": { "order": "desc" } }, "query": { "bool": { "must": [ { "match": { "publish_authory": "区块链" } }, { "range": { "publish_date": { "gte": "2019-06-11 00:00:00" } } } ] } } ES会检索返回包含--区,块,链任意一个词的结果。 精准查询可以使用match_phrase,其实ES在查询时还是会进行分词,但是还会加上一个条件,就是各个词的顺序,只有和所给词的顺序和位置一样才会返回。(term不会分词,但是ES中的索引在存储时,中文会被分词到单个词,所以如果使用term检索,要确保字段是no analyzed的)(4)多条件查询,多个条件查询是可以使用bool来组合查询条件。比如: select * from table where is_valid = true and name ='Tome ' "query" : { "bool" : { "must": [ {"match" : { "is_valid" : true} },{"match" : { “name" : "Tome"} } ] } } select * from table where is_valid = true and ( name = 'Tome' and class != '2班‘); ”query" : { "bool" : { "must" : [ {"match" : { "is_valid" : true}, "bool" : { "must" : {"match" :{ “name” : "Tome" } },"must_not" :{"match" : {"class": "2班" } } } } ] } } 一个bool是构成一个()组合查询条件,must相当and,should相当于or,must_not 相当于不等于。
可以根据查询条件组合query,需要将query转为json字符串,在转换的过程中,需要注意如果查询条件不连续,产生的索引数组,需要使用array_value,转为连续的索引数组,这样在转为json 以后就不会出现索引数字存在。带有汉字的查询条件,在转为json的时候,可以使用json_encode($data, JSON_UNESCAPED_UNICODE); //必须PHP5.4+ ----不转译汉字。