1、全文搜索(一种传统数据库很难实现的功能)数据库
咱们将会搜索全部喜欢“rock climbing”的员工: GET /megacorp/employee/_search { "query" : { "match" : { "about" : "rock climbing" } } }
你能够看到咱们使用了以前的match
查询,从about
字段中搜索"rock climbing",咱们获得了两个匹配文档:json
{ ... "hits": { "total": 2, "max_score": 0.16273327, "hits": [ { ... "_score": 0.16273327, <1> "_source": { "first_name": "John", "last_name": "Smith", "age": 25, "about": "I love to go rock climbing", "interests": [ "sports", "music" ] } }, { ... "_score": 0.016878016, <2> "_source": { "first_name": "Jane", "last_name": "Smith", "age": 32, "about": "I like to collect rock albums", "interests": [ "music" ] } } ] } }
默认状况下,Elasticsearch根据结果相关性评分来对结果集进行排序, 结果相关性评分就是文档与查询条件的匹配程度。设计
可是为何Jane Smith
也会出如今结果里呢?缘由是“rock”在她的abuot
字段中被说起了。由于只有“rock”被说起而“climbing”没有,因此她的_score
要低于John。rest
2、短语搜索code
全文搜索容许咱们在字段中搜索单独的一个词,这挺好的,可是有时候你想要确切的匹配若干个单词或者短语(phrases)。例如咱们想要查询同时包含"rock"和"climbing"(而且是相邻的)的员工记录。orm
GET /megacorp/employee/_search { "query" : { "match_phrase" : { "about" : "rock climbing" } } }
毫无疑问,该查询返回John Smith的文档:排序
{ ... "hits": { "total": 1, "max_score": 0.23013961, "hits": [ { ... "_score": 0.23013961, "_source": { "first_name": "John", "last_name": "Smith", "age": 25, "about": "I love to go rock climbing", "interests": [ "sports", "music" ] } } ] } }
3、查询高亮显示文档
Elasticsearch中高亮片断是很是容易的,让咱们在以前的语句上增长highlight
参数:it
{ "query": { "match_phrase": { "company_name": "苗会" } }, "highlight": { "fields": { "company_name": {} } } }
当咱们运行这个语句时,会命中与以前相同的结果,可是在返回结果中会有一个新的部分叫作highlight,
而且用<em></em>
来标识匹配到的单词。ast
{ "_index": "miaotu_formal", "_type": "company_info_and_type", "_id": "234", "_score": 3.3942661, "_source": { "company_name": "中苗会", "short_name": "中苗会", "type_name": "景观设计" }, "highlight": { "company_name": [ "中<em>苗</em><em>会</em>" ] } }