ES 常用查詢語法

Polin Chen
elkplus
Published in
4 min readMay 30, 2017

elasticsearch 是採用 Apache上Lucene的查詢語法,包含欄位查詢、模糊查詢、鄰近查詢、範圍查詢、語詞權值群組查詢

字詞定義

  • 單字例如 “test” 或 “hello”
  • 雙引號包住的片語,例如 “hello dolly”
  • 多語詞可以用布林運算子整合在一起來建構一個複雜的查詢

ES的查詢語法範例

欄位的查詢

  • 查詢status 包含active 值
status:active
  • 查詢title 欄位中包含 quick 或是brown 的欄位, 其中的O 可以省列
title:(quick OR brown)
title:(quick brown)
  • 精準查詢 author 欄位中包含 john smith
author:”John Smith”
  • 多欄位的查詢
field1:query_term OR field2:query_term 
  • Wildcard 查詢, 可以使用wildcard 進行查詢
field:(qu?ck bro*)

Ranges 的查詢

範圍的查詢可以指定日期、數字或是字串,同時可以使用

[min TO max] : 查詢指定範圍內
{min TO max} : 查詢指定範圍外

範圍的查詢範例

  • All days in 2012:
date:[2012–01–01 TO 2012–12–31]
  • Numbers 1..5
count:[1 TO 5]
  • Tags 介於alpha 和omega, 但是不包含alpha 和omega:
tag:{alpha TO omega}
  • 數字從10 以上的值
count:[10 TO *]
  • 2012年前的日期
date:{* TO 2012–01–01}
  • [ 和} 混合查詢: 數字從1開始,但是不包含5 的值
count:[1 TO 5}
  • 數字範圍查詢:
age:>10
age:>=10
age:<10
age:<=10
age:(>=10 AND <20)
age:(+>=10 +<20)

組合查詢:

(quick OR brown) AND fox
status:(active OR pending) title:(full text search)

查詢有包含這個欄位的內容

如果有時候有些欄位有內容, 有時候沒有內容, 以下例子是查詢pname3 欄位中, pname3 有內容的值。

_exists_:pname3

保留字

如果需要查詢保留字,必須加上backslash 以判別保留字, 例如要查詢 (1+1)=2, 語法為 \(1\+1\)\=2.

保留字:

 + — = && || > < ! ( ) { } [ ] ^ “ ~ * ? : \ /

IIS log 的常用的查詢範例

  • 查詢cs_status 欄位 相關查詢
cs_status:404cs_status:(404 OR 500)cs_status:(400 TO 499)
  • 查詢WEB07-IIS1 staus 404 和WEB08-IIS2 status 500 的內容
s_computername: WEB07 AND cs_status:400s_computername: WEB08 AND cs_status:500(s_computername: WEB08 AND cs_status:400 ) AND @timestamp:[2017-04-02 TO 2017-04-23]
  • 查詢PriceService.svc 相關內容
cs_uri_stem_name:PriceService.svccs_uri_stem_name:PriceService.svc AND time_taken:(>=200)cs_uri_stem_name:PriceService.svc AND time_taken:(>=5000 AND <=10000)cs_uri_stem_name:PriceService.svc AND time_taken:(>=5000 AND <=10000)  AND @timestamp:[2017-04-02 TO 2017-04-23]cs_uri_stem_name:(PriceService.svc OR OperationService.svc) AND time_taken:(>=5000 AND <=10000) AND @timestamp:[2017-04-02 TO 2017-04-23]

參考資料

--

--