【问题标题】:elasticsearch autosuggest returning tricky JSONelasticsearch 自动建议返回棘手的 JSON
【发布时间】:2016-09-28 22:31:39
【问题描述】:

我正在运行一个 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 上运行函数

【问题讨论】:

  • postSuggest 是一个数组(括号,[..]),其中包含一个对象(大括号,{..})。您需要先访问数组的索引——postSuggest[0].options。 – Access / process (nested) objects, arrays or JSON
  • 解决了我的问题,谢谢。我从来没有注册过它是一个数组。

标签: javascript json node.js mongodb elasticsearch


【解决方案1】:

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

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

下面这个sn-p可能有用

 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2017-09-11
    • 2014-08-15
    相关资源
    最近更新 更多