【问题标题】:How to index a hierarchical data?如何索引分层数据?
【发布时间】:2015-12-26 16:35:35
【问题描述】:

我有一些可以通过两种数据结构表示的分层数据。

第一个是多级 JSON 对象,如下所示:

[
    { 
        "text": "Item 1, "children": [
            {"text": "Nested item 1"}, 
            {"text": "Nested item 2"}] 
    },
    {
        "text": "Item 2", "children": []
    }
]

第二个结构是一个数组。此数组的项由id-parentId 绑定。

[
    {id: 1, text: "Item 1", parentId: null},
    {id: 2, text: "Nested item 1", parentId: 1}
]

我需要通过一些子字符串过滤这些数据。

为了实现这个功能,我想创建一些搜索索引。然后为创建的索引提供过滤操作。

创建搜索索引的主要原因是使用单一过滤算法而不是两种不同的方法来过滤分层数据和id-parentId 列表。

那么,问题是应该有什么格式的搜索索引?目前,我使用这样的东西:

[
    {id: 1, text: "item 1", parentKey: null, childrenKeys: [2,3]},
    {id: 2, text: "child 1", parentKey: 1, childrenKeys: []},
    {id: 3, text: "child 2", parentKey: 1, childrenKeys: []}  
]

优点:每个项目都有指向父母和孩子的链接。

缺点:如果源数据结构是层次结构,我必须手动为项目生成键。

【问题讨论】:

  • “手动”是什么意思?
  • 多级JSON结构默认没有item key。所以我必须从源 JSON 对象为每个节点创建键,然后将其添加到搜索索引中。
  • 请提供此类索引的一些具体使用场景。例如,您将仅按完整字符串值搜索,还是按子字符串搜索?这些子字符串可以位于字符串中的任何位置,还是仅位于字符串的开头或结尾?
  • 你有什么限制,比如数据与索引大小的比例?
  • 我想查找包含一些子字符串的项目。例如,如果 substring 是 'abc',则应将 item.text: 'abcd' 添加到搜索结果中。

标签: algorithm hierarchy hierarchical-data


【解决方案1】:

只需同时处理这两种格式,处理映射到单一格式的麻烦是不值得的。

下面我使用了 Array.prototype.reduce 函数(我可以使用 Array.prototype.filter,但是我不得不连接递归调用的结果数组和/或将函数 args 添加到绑定中)。

JSFiddle http://jsfiddle.net/5q4cdevt/

/* @this {string} search value */ 
function reduceContains(result, obj) {
    if(obj.text.indexOf(this) >= 0) { 
        result.push(obj); 
    }
    if(obj.children) {
        obj.children.reduce(reduceContains.bind(this), result);
    }
    return result;
}

console.log([
    { 
        "text": "Item 1", "children": [
            {"text": "Nested item 1"}, 
            {"text": "Nested item 2"}] 
    },
    {
        "text": "Item 2", "children": []
    }
].reduce(reduceContains.bind("Nested"), []));

console.log([
    {id: 1, text: "Item 1", parentId: null},
    {id: 2, text: "Nested item 1", parentId: 1}
].reduce(reduceContains.bind("Nested"), []));

【讨论】:

  • 感谢您的回复@Louis Ricci! Array.prototype.reduce 是个好主意!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 2015-01-02
相关资源
最近更新 更多