elasticsearch autosuggest返回棘手的JSON

时间:2016-05-31 04:19:25

标签: javascript json node.js mongodb elasticsearch

我正在运行一个node.js服务器,该服务器将查询发送到elasticsearch实例。以下是查询返回的JSON示例:

{
    "took": 2,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 9290,
        "max_score": 0,
        "hits": []
    },
    "suggest": {
        "postSuggest": [
            {
                "text": "a",
                "offset": 0,
                "length": 1,
                "options": [
                    {
                        "text": "Academic Librarian",
                        "score": 2
                    },
                    {
                        "text": "Able Seamen",
                        "score": 1
                    },
                    {
                        "text": "Academic Dean",
                        "score": 1
                    },
                    {
                        "text": "Academic Deans-Registrar",
                        "score": 1
                    },
                    {
                        "text": "Accessory Designer",
                        "score": 1
                    }
                ]
            }
        ]
    }
}

我需要创建一个包含每个作业标题的数组作为字符串。我遇到了这种奇怪的行为,我无法弄明白。每当我尝试从JSON中提取值时,我都不能低于options或者所有内容都会以未定义的方式返回。

例如:

arr.push(results.suggest.postSuggest)会推送您期望的内容:postSuggest中的所有内容。

arr.push(results.suggest.postSuggest.options)将会显示为未定义,即使我在没有.options的情况下运行它时也可以看到它。对于.options以下的任何内容也是如此。

我认为可能是因为.options是一种作用于变量的内置函数,所以不是将选项视为JSON而是尝试在results.suggest.postSuggest上运行函数

1 个答案:

答案 0 :(得分:1)

  

arr.push(results.suggest.postSuggest.options)

postSuggest是一个对象数组。options里面的postSuggest也是一个对象数组。所以首先你需要postSuggest[0]然后获得postSuggest postSuggest[0].options获取options

的数组

以下代码段可以是usefule

 var myObj = {..}
// used jquery just to demonstrate postSuggest  is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest  //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
  document.write("<pre>Score is "+ item.score + " Text</pre>")
})

Jsfiddle