2013-03-29 167 views
2

我在學習Elasticsearch,所以我不確定這個查詢是否正確。我已檢查過數據是否已編入索引,但我沒有收到任何匹配。我究竟做錯了什麼?這不應該在創作者的名字是史蒂夫的汽車上受到打擊嗎?查詢嵌套文檔Elasticsearch

builder 
.startObject() 
    .startObject("car") 
     .field("type", "nested") 
     .startObject("properties") 
      .startObject("creators") 
       .field("type", "nested")      
      .endObject()     
     .endObject() 
    .endObject() 
.endObject(); 


{ 
    "query": { 
    "bool": { 
     "must": [ 
     { 
      "term": { 
      "car.creators.name": "Steve" 
      } 
     } 
     ], 
     "must_not": [], 
     "should": [] 
    } 
    }, 
    "from": 0, 
    "size": 50, 
    "sort": [], 
    "facets": {} 
} 

回答

8

首先,爲了尋找你需要使用nested query嵌套字段:

curl -XDELETE localhost:9200/test 
curl -XPUT localhost:9200/test -d '{ 
    "settings": { 
     "index.number_of_shards": 1, 
     "index.number_of_replicas": 0 
    }, 
    "mappings": { 
      "car": { 
       "properties": { 
        "creators" : { 
         "type": "nested", 
         "properties": { 
          "name": {"type":"string"} 
         } 
        } 
       } 
      } 
     } 
    } 
} 
' 
curl -XPOST localhost:9200/test/car/1 -d '{ 
    "creators": { 
     "name": "Steve" 
    } 
} 
' 
curl -X POST 'http://localhost:9200/test/_refresh' 
echo 
curl -X GET 'http://localhost:9200/test/car/_search?pretty' -d ' { 
    "query": { 
     "nested": { 
      "path": "creators", 
      "query": { 
       "bool": { 
        "must": [{ 
         "match": { 
          "creators.name": "Steve" 
         } 
        }], 
        "must_not": [], 
        "should": [] 
       } 
      } 
     } 
    }, 
    "from": 0, 
    "size": 50, 
    "sort": [], 
    "facets": {} 
} 
' 

如果car.creators.name使用標準分析儀指數則因爲字Steve被收錄爲steve{"term": {"creators.name": "Steve"}}不會找到任何東西而term query不執行分析。所以,最好用match query{"match": {"creators.name": "Steve"}}來代替它。

+0

謝謝!我必須將路徑字段移出查詢對象,並在路徑中插入「創建者」,並僅在該術語中使用creators.name。這聽起來是錯的還是對的? – LuckyLuke

+0

是的,你是對的。路徑應與查詢處於同一級別,並應包含「car.creators」。我已經更新了這個例子。不確定該術語中的creators.name。你的情況是汽車嗎? – imotov

+0

是的,汽車是一種類型?由於我正在學習Elasticsearch,你會介意解釋爲什麼我不需要它,並設法使它與它一起工作嗎? – LuckyLuke