2016-05-23 92 views
1

我必須在同一個查詢字符串的多個字段上搜索關鍵字。使用相同的查詢字符串在多個字段上匹配和匹配 - 彈性搜索(嵌套)

"bool": { 
     "should": [ 
      { 
       "match": { 
          "ABC": "Apple" 
         } 
      }, 
      { 
       "match": { 
          "XYZ": "Apple" 
         } 
      } 
     ] 
    } 

當我寫的查詢DSL,它已被翻譯成multimatch查詢(不知道上面的代碼和DSL相同)

.Bool(b => b 
.Should(sh => sh 
.MultiMatch(c => c 
.Fields(f => f.Field(p => p.ABC).Field("XYZ")) 
.Query(keyz))))) 

同樣地,我想寫一個DSL查詢,但我想做match_phrase操作。有人能幫我解決這個問題嗎?

TIA

回答

2

鑑於文檔類型

public class Document 
{ 
    public string ABC { get; set; } 
    public string XYZ { get; set; } 
} 

這將是

var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200")); 
var defaultIndex = "default-index"; 
var connectionSettings = new ConnectionSettings(pool) 
     .DefaultIndex(defaultIndex) 
     .DefaultFieldNameInferrer(p => p); 

var client = new ElasticClient(connectionSettings); 
var keyz = "Apple"; 

client.Search<Document>(s => s 
    .Query(q => q 
     .Bool(b => b 
      .Should(sh => sh 
       .Match(c => c 
        .Field(p => p.ABC) 
        .Query(keyz) 
       ), 
        sh => sh 
       .Match(c => c 
        .Field(p => p.XYZ) 
        .Query(keyz) 
       ) 
      ) 
     ) 
    ) 
); 

您可以通過taking advantage of operator overloading

client.Search<Document>(s => s 
    .Query(q => q 
     .Match(c => c 
      .Field(p => p.ABC) 
      .Query(keyz) 
     ) 
     || q.Match(c => c 
      .Field(p => p.XYZ) 
      .Query(keyz) 
     ) 
    ) 
); 
縮短這個

Both產生

{ 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "match": { 
      "ABC": { 
       "query": "Apple" 
      } 
      } 
     }, 
     { 
      "match": { 
      "XYZ": { 
       "query": "Apple" 
      } 
      } 
     } 
     ] 
    } 
    } 
} 
+0

嗨Russ。謝謝您的幫助。我可以知道爲什麼使用「.DefaultFieldNameInferrer(p => p)」,它有什麼用? 而我實際上首先嚐試運行match_phrase,如果match_phrase查詢中的匹配值爲0,則計劃運行匹配查詢。 – ASN

+0

查看'.DefaultFieldNameInferrer()'的文檔 - https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/field-inference.html#camel-casing。它允許您控制如何從您的POCO屬性名稱推斷字段名稱。你可以用'bool'查詢同時運行'match_phrase'和'match' –

+0

謝謝Russ。但是我想首先在兩個字段上運行match_phrase,如果結果爲0,則希望再次在這些字段上運行匹配查詢。我不打算在一個場上做一個match_phrase,而在另一個場上做一個match。我的多匹配DSL查詢是否錯誤? – ASN