ElasticSearch學習問題記錄——nested查詢不到數據


通過代碼創建了索引名稱為demoindex,索引類型為school,以下是索引類型的數據映射結構:

{
    "state": "open",
    "settings": {
        "index.number_of_replicas": "1",
        "index.number_of_shards": "5",
        "index.version.created": "901399",
        "index.uuid": "-Z5eg5nnSp-VsNfUZAMN-A"
    },
    "mappings": {
        "school": {
            "properties": {
                "id": {
                    "store": true,
                    "analyzer": "ik",
                    "type": "string"
                },
                "name": {
                    "store": true,
                    "analyzer": "ik",
                    "type": "string"
                },
                "age": {
                    "store": true,
                    "type": "integer"
                },
                "studentList": {
                    "properties": {
                        "sex": {
                            "store": true,
                            "analyzer": "ik",
                            "type": "string"
                        },
                        "studentId": {
                            "store": true,
                            "analyzer": "ik",
                            "type": "string"
                        },
                        "studentName": {
                            "store": true,
                            "analyzer": "ik",
                            "type": "string"
                        }
                    },
                    "type": "nested"
                }
            }
        }
    },
    "aliases": []
}

數據結構存在嵌套關系,學校屬性中包含嵌套屬性studentList,存放學校的學生。下面是demoindex中的所有數據:

使用head進行如下查詢,結果發現結果查不出來。這里我勾選了【顯示查詢語句】。

找不到答案只好求助於《Elasticsearch服務器開發》。經過查閱得知nested類型的嵌套查詢需要使用專用搜索格式。先貼出原書描述:

{
"cloth" : {
"properties" : {
"name" : {"type" : "string", "index" : "analyzed"},
"variation" : {
"type" : "nested",
"properties" : {
"size" : {"type" : "string", "index" : "not_analyzed"},
"color" : {"type" : "string", "index" : "not_analyzed"}
}
}
}
}
}
可以看到,我們在 cloth類型中引入了新對象 variation,它是嵌套的( type屬性設置為
nested),表示想為嵌套文檔建立索引。現在修改文檔,添加 variation對象,其中有兩個屬性:
size和 color。示例產品將如下所示:
{
"name" : "Test shirt",
"variation" : [
{ "size" : "XXL", "color" : "red" },
{ "size" : "XL", "color" : "black" }
]
}
組織文檔結構,以便每個尺寸及其匹配顏色成為一個獨立文檔。然而,如果執行之前的查詢,
將無任何文檔返回。這是因為,對於嵌套文件,需要使用專門的查詢。因此,查詢如下(當然,
我們已經再次創建了索引和類型):
curl -XGET 'localhost:9200/shop/cloth/_search?pretty=true' -d '{
"query" : {
"nested" : {
"path" : "variation",
"query" : {
"bool" : {
"must" : [
{ "term" : { "variation.size" : "XXL" } },
{ "term" : { "variation.color" : "black" } }
]
}
}
}
}
}'
現在,上述查詢將無法返回索引中的文檔,因為無法找到尺寸 XXL且顏色為黑色的嵌套文檔。
這里簡單討論一下我們的查詢,可以看到,我們使用 nested查詢來查詢嵌套文檔。 path屬性指
定了嵌套對象的名稱(可以使用多個名稱)。 nested類型包括了一個標准查詢部分。應注意的是,
在嵌套對象中為字段名稱指定完整的路徑,在多級嵌套中很方便操作(這也是可能的)。

根據書中介紹將使用head的復合查詢方式進行如下查詢。成功,數據出現了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM