前面的文章中主要介绍了Elasticsearch的安装及基本的CRUD操做,在使用Elasticsearch的时候,大部分是使用他的搜索,本次咱们就来了解更多搜索的API。html
这种方式用得很少,通常用得比较多的是Request Body Search。elasticsearch
URI Search能够使用GET,也能够使用POST,基本的语法以下ide
GET /<target>/_search?xxx POST /<target>/_search?xxx
一些例子ui
// 查询的索引是movies,profile=true至关于MySQL的explain,df指定查询的字段,q指定查询的内容,from从第几条开始,size返回多少条,sort指定排序规则(可选值asc desc),timeout指定搜索的超时时间 GET movies/_search?q=2012&df=title&from=0&size=3&sort=movieId:desc&timeout=1s { "profile": "true" } // 对q+dp的简化方式,查询title字段,值为2012的文档 GET movies/_search?q=title:2012 // 括号内能够文本会进行分词搜索,默认是OR,能够使用AND,还能够使用“+ -”(“+”要用“%2B”进行转义),“+”表示必须有,“-”必须没有 GET movies/_search?q=title:(beautiful mind) GET movies/_search?q=title:(beautiful AND mind) GET movies/_search?q=title:(%2Bbeautiful %2Bmind) // 范围查询 GET movies/_search?q=movieId:>1900 GET movies/_search?q=movieId:[2 TO 5] // 正则匹配 GET movies/_search?q=title:beauti* GET movies/_search?q=title:beau*ful // 近似查询,“~2”与下文中match_phrase的“slop 2”一致,具体含义参考下文 GET movies/_search?q=title:"Corrupt beautiful"~2
GET movies/_search { "profile": "true", "_source": ["movieId", "title","genres"], "sort": [{"movieId": "desc"}], "from": 0, "size": 3, "query": { "match_all": {} } }
GET movies/_search { "profile": "true", "_source": ["movieId", "title","genres"], "sort": [{"movieId": "desc"}], "from": 0, "size": 3, "query": { "match": { "title":{ "query":"beautiful mind", "operator": "or" } } } }
会进行分词匹配,能够指定operator,可选值(and or not),默认是orcode
GET movies/_search { "query": { "match_phrase": { "title":{ "query":"beautiful mind", "slop": 1 } } } }
slop等同于上面的近似查询“~1”。短语匹配,相似SQL中的like,但能够设置slop实现近似匹配,表示移动多少个词能够进行匹配。htm
好比有文本“beautiful mind people”,搜索短语“people beautiful”须要移动3次才能匹配(beautiful第一次移到mind那个位置,第二次移到people那个位置,第三次移到people的后面);而搜索短语“beautiful people”须要移动1次就能匹配。排序
GET movies/_search { "query": { "query_string": { "default_field": "title", "query": "(beautiful AND mind) OR (beautiful AND people)" } } }
query中的语法支持逻辑符合(AND OR NOT)索引
GET movies/_search { "profile": "true", "query": { "simple_query_string": { "query": "beautiful mind", "fields": ["title"] } } } GET movies/_search { "profile": "true", "query": { "simple_query_string": { "query": "beautiful +mind", "fields": ["title"] } } }
相似query_string,但会忽略错误的语法。文档
query中不支持“AND OR NOT”,会被当作字符串处理。支持的逻辑处理是“+ | -”,分别表明“AND OR NOT”字符串
能够指定default_operator,支持AND OR。
query中的逻辑处理与default_operator的逻辑符合一块儿用,会以query中的逻辑处理为准。