Elasticsearch Search API

前言

前面的文章中主要介紹了Elasticsearch的安裝及基本的CRUD操做,在使用Elasticsearch的時候,大部分是使用他的搜索,本次咱們就來了解更多搜索的API。html

URI Search

這種方式用得很少,通常用得比較多的是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

Request Body Search

基本語法

GET movies/_search
{
  "profile": "true",
  "_source": ["movieId", "title","genres"], 
  "sort": [{"movieId": "desc"}],
  "from": 0,
  "size": 3,
  "query": {
    "match_all": {}
  }
}
  • movies 查詢的索引
  • profile 至關於MySQL中的explain
  • _source 是要返回的字段
  • sort 指定排序的字段
  • from 從第幾條開始,默認是0
  • size 返回多少條數據,默認是10
  • query 指定查詢的方式,可選值通常有(match_all, match, match_phrase, query_string, simple_query_string),match_all查詢全部

match

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

match_phrase

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次就能匹配。排序

query_string

GET movies/_search
{
  "query": {
    "query_string": {
      "default_field": "title",
      "query": "(beautiful AND mind) OR (beautiful AND people)"
    }
  }
}

query中的語法支持邏輯符合(AND OR NOT)索引

simple_query_string

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中的邏輯處理爲準。

參考資料

相關文章
相關標籤/搜索