在Rails使用Sunspot習慣了,可能對Solr的原生查詢完全不了解,其實Sunspot對Solr的查詢進行了非常完美的封裝,Sunspot的查詢會轉換為這樣的請求(參見solr.log):
INFO - 2016-01-30 20:19:20.893; org.apache.solr.core.SolrCore; [collection1] webapp=/solr path=/select params={fl=*+score&sort=updated_at_d+desc&start=0&q=安徽&qf=title_text+content_text&wt=ruby&fq=type:Bid\:\:Info&fq=close_tag_i:0&rows=20&defType=edismax} hits=1 status=0 QTime=20
而
{fl=*+score&sort=updated_at_d+desc&start=0&q=安徽&qf=title_text+content_text&wt=ruby&fq=type:Bid\:\:Info&fq=close_tag_i:0&rows=20&defType=edismax}
這個才是Solr服務器真正能夠理解的查詢參數,當我們遇到使用Sunspot無法解決的問題的時候,就需要直接越過Sunspot來調用Solr了。Solr接受的是HTTP協議的接口調用,因此查詢的參數都是通過URL參數來進行傳遞,而且參數中的值都需要進行URL的編碼。
下面來詳細介紹Solr的查詢語法。
Solr默認有三種查詢解析器(Query Parser):
- Standard Query Parser
- DisMax Query Parser
- Extended DisMax Query Parser (eDisMax)
第一種是標準的Parser,最后一種是最強大的,也是Sunspot默認使用的Parser。
支持的參數:
- defType: 選擇查詢解析器類型,例如dismax, edismax
- q:主查詢參數(field_name:value)
- sort:排序,例如score desc,price asc
- start:起始的數據偏移offset,用于分頁
- raws:一次返回的數量,用于分頁
- fq:filter query 返回結果的過濾查詢
- fl:fields to list 返回的字段(*, score)
- debug:返回調試信息,debug=timing,debug=results
- timeAllowed:超時時間
- wt:response writer返回的響應格式
下面是DisMax Parser可以使用的:
- qf:query fields,指定查詢的字段,指定solr從哪些field中搜索,沒有值的時候使用df
- mm:最小匹配比例
- pf:phrase fields
- ps:phrase slop
- qs:query phrase slop
特殊符號意義:
- ?:te?t 單個字符匹配
- *:tes* 多個字符匹配
- ~:fuzzy searches(模糊匹配),roam~,roams/foam/foams
- count:{1 TO 10}:range search 范圍檢索
- ^:Boosting a Term(升級權重),jakarta^4 apache, "酒店"^4 "賓館"
- ^=:Constant Score with(指定分數),(description:blue OR color:blue)^=1.0 text:shoes
邏輯操作
- AND 或者 &&
- NOT 或者 !
- OR 或者 !!
- + 必須滿足
- - 剔除,比如 title: -安徽,返回的是title中不含有"安徽"的所有結果
回顧復習
fl=*+score
sort=updated_at_d+desc
start=0
q=安徽
qf=title_text+content_text
wt=ruby
fq=type:Bid\:\:Info
fq=close_tag_i:0
rows=20
defType=edismax
夏書記的需求:
q=(酒店 OR type_i:0)
Solr的查詢可以在圖形界面中進行測試:
Paste_Image.png