分类: 大数据
2023-01-30 10:50:51
作者:京东物流 马瑞
trie 树,即字典树,又称单词查找树或键树,是一种树形结构,典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,{banned}最佳大限度地减少无谓的字符串比较,查询效率比哈希树高。
trie, also called digital tree and sometimes radix tree or prefix tree (as they can be searched by prefixes), is a kind of search tree—an ordered tree data structure that is used to store a dynamic set or associative array where the keys are usually strings. it is one of those data-structures that can be easily implemented.
{banned}最佳大限度地减少无谓的字符串比较,查询效率比较高。核心思想是空间换时间,利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
以字符串”hi” 和” 经海路” 的数据为例:
java 的数据结构定义:
@data public class trietreenode { private character data; private map children; private boolean isend; // 前缀,冗余信息,可选 private string prefix; // 后缀,冗余信息,可选 private string suffix;
}
如果只是处理 26 个英文字符,data 可以通过 children 数组是否为空来判断。如果处理程序,默认 children 为空来判断是否为{banned}最佳后一个节点,则 isend 字段可以省略。
前缀 prefix 和 suffix 可以在数据处理的时候,方便拿到当前节点前缀和后缀信息,如果不需要可以去除。
public class keyword implements serializable { /**
* 关键词内容
*/ private string word; //其他省略 }
public class kwseeker { /**
* 所有的关键词
*/ private set sensitivewords; /**
* 关键词树
*/ private map<string, map> wordstree = new concurrenthashmap<string, map>(); /**
* {banned}最佳短的关键词长度。用于对短于这个长度的文本不处理的判断,以节省一定的效率
*/ private int wordleastlen = 0; //其他处理方法,省略 }
/**
* 将指定的词构造到一棵树中。
*
* @param tree 构造出来的树
* @param word 指定的词
* @param keyword 对应的词
* @return
*/ public static map<string, map> maketreebyword(map<string, map> tree, string word,
keyword keyword) { if (stringutils.isempty(word)) {
tree.putall(endtagutil.buind(keyword)); return tree;
} string next = word.substring(0, 1); map<string, map> nexttree = tree.get(next); if (nexttree == null) {
nexttree = new hashmap<string, map>();
} // 递归构造树结构 tree.put(next, maketreebyword(nexttree, word.substring(1), keyword)); return tree;
}
对关键词字符串,逐个字符进行构建。
/**
* 构造、生成词库树。并返回所有敏感词中{banned}最佳短的词的长度。
*
* @param sensitivewords 词库
* @param wordstree 聚合词库的树
* @return 返回所有敏感词中{banned}最佳短的词的长度。
*/ public int generaltree(set sensitivewords, map wordstree) { if (sensitivewords == null || sensitivewords.isempty() || wordstree == null) { return 0;
}
wordstreetmp.clear(); int len = 0; for (keyword kw : sensitivewords) { if (len == 0) {
len = kw.getwordlength();
} else if (kw.getwordlength() < len) {
len = kw.getwordlength();
}
analysisutil
.maketreebyword(wordstreetmp, stringutils.trimtoempty(kw.getword()), kw);
}
wordstree.clear();
wordstree.putall(wordstreetmp); return len;
}
/**
* 将文本中的关键词提取出来。
*/ public list process(map<string, map> wordstree, string text,
abstractfragment fragment, int minlen) { // 词的前面一个字 string pre = null; // 词匹配的开始位置 int startposition = 0; // 返回结果 list rs = new arraylist(); while (true) { try { if (wordstree == null || wordstree.isempty() || stringutils.isempty(text)) { return rs;
} if (text.length() < minlen) { return rs;
} string chr = text.substring(0, 1);
text = text.substring(1); map<string, map> nextword = wordstree.get(chr); // 没有对应的下一个字,表示这不是关键词的开头,进行下一个循环 if (nextword == null) {
pre = chr; continue;
}
list keywords = lists.newarraylist();
keyword kw = analysisutil.getsensitiveword(chr, pre, nextword, text, keywords); if (keywords == null || keywords.size() == 0) { // 没有匹配到完整关键字,下一个循环 pre = chr; continue;
} for (keyword tmp : keywords) { // 同一个word多次出现记录在一起 sensitivewordresult result = new sensitivewordresult(startposition, tmp.getword());
int index = rs.indexof(result); if (index > -1) {
rs.get(index).addposition(startposition, tmp.getword());
} else {
rs.add(result);
}
} // 从text中去除当前已经匹配的内容,进行下一个循环匹配 // 这行注释了,避免"中国人",导致"国人"。搜索不出来,逐个字符遍历 // text = text.substring(kw.getwordlength() - 1); pre = kw.getword().substring(kw.getwordlength() - 1, kw.getwordlength()); continue;
} finally { if (pre != null) {
startposition = startposition pre.length();
}
}
}
} /**
* 查询文本开头的词是否在词库树中,如果在,则返回对应的词,如果不在,则返回null。return 返回找到的{banned}最佳长关键词
*
* @param append 追加的词
* @param pre 词的前一个字,如果为空,则表示前面没有内容
* @param nextwordstree 下一层树
* @param text 剩余的文本内容
* @param keywords 返回的keywords,可能多个
* @return 返回找到的{banned}最佳长关键词
*/ public static keyword getsensitiveword(string append, string pre, map<string, map> nextwordstree, string text, list keywords) { if (nextwordstree == null || nextwordstree.isempty()) { return null;
} map<string, object> endtag = nextwordstree.get(endtagutil.tree_end_tag); // 原始文本已到末尾 if (stringutils.isempty(text)) { // 如果有结束符,则表示匹配成功,没有,则返回null if (endtag != null) {
keywords.add(checkpattern(getkeyword(append, endtag), pre, null)); return checkpattern(getkeyword(append, endtag), pre, null);
} else { return null;
}
} string next = text.substring(0, 1); string suffix = text.substring(0, 1); map<string, map> nexttree = nextwordstree.get(next); // 没有遇到endtag,继续匹配 if (endtag == null) { if (nexttree != null && nexttree.size() > 0) { // 没有结束标志,则表示关键词没有结束,继续往下走。 return getsensitiveword(append next, pre, nexttree, text.substring(1), keywords);
} // 如果没有下一个匹配的字,表示匹配结束! return null;
} else { // endtag , 添加关键字 keyword tmp = getkeyword(append, endtag);
keywords.add(checkpattern(tmp, pre, suffix));
} // 有下一个匹配的词则继续匹配,一直取到{banned}最佳大的匹配关键字 keyword tmp = null; if (nexttree != null && nexttree.size() > 0) { // 如果大于0,则表示还有更长的词,继续往下找 tmp = getsensitiveword(append next, pre, nexttree, text.substring(1), keywords); if (tmp == null) { // 没有更长的词,则就返回这个词。在返回之前,先判断它是模糊的,还是精确的 tmp = getkeyword(append, endtag);
} return checkpattern(tmp, pre, suffix);
} // 没有往下的词了,返回该关键词。 return checkpattern(getkeyword(append, endtag), pre, suffix);
}
思路是对某个字符串 text,逐个字符 ch,获取 ch 对应的词库树的 children,然后获取匹配到的单个或多个结果,将匹配到的关键词在 text 中的开始和结束下标进行记录,如后续需要 html 标记,或者字符替换可直接使用。如果未能在词库树中找到对应的 ch 的 children,或者词库树的 children 未能匹配到去除 ch 的子字符串,则继续循环。具体可再详细读一下代码。
redis 实现了不定长压缩前缀的 radix tree,用在集群模式下存储 slot 对应的的所有 key 信息。
/* representation of a radix tree as implemented in this file, that contains
* the strings "foo", "foobar" and "footer" after the insertion of each
* word. when the node represents a key inside the radix tree, we write it
* between [], otherwise it is written between ().
*
* this is the vanilla representation:
*
* (f) ""
* \
* (o) "f"
* \
* (o) "fo"
* \
* [t b] "foo"
* / \
* "foot" (e) (a) "foob"
* / \
* "foote" (r) (r) "fooba"
* / \
* "footer" [] [] "foobar"
*
* however, this implementation implements a very common optimization where
* successive nodes having a single child are "compressed" into the node
* itself as a string of characters, each representing a next-level child,
* and only the link to the node representing the last character node is
* provided inside the representation. so the above representation is turned
* into:
*
* ["foo"] ""
* |
* [t b] "foo"
* / \
* "foot" ("er") ("ar") "foob"
* / \
* "footer" [] [] "foobar"
*
* however this optimization makes the implementation a bit more complex.
* for instance if a key "first" is added in the above radix tree, a
* "node splitting" operation is needed, since the "foo" prefix is no longer
* composed of nodes having a single child one after the other. this is the
* above tree and the resulting node splitting after this event happens:
*
*
* (f) ""
* /
* (i o) "f"
* / \
* "firs" ("rst") (o) "fo"
* / \
* "first" [] [t b] "foo"
* / \
* "foot" ("er") ("ar") "foob"
* / \
* "footer" [] [] "foobar"
*
* similarly after deletion, if a new chain of nodes having a single child
* is created (the chain must also not include nodes that represent keys),
* it must be compressed back into a single node.
*
*/ #define rax_node_max_size ((1<<29)-1) typedef struct raxnode { uint32_t iskey:1; /* does this node contain a key? */ uint32_t isnull:1; /* associated value is null (don't store it). */ uint32_t iscompr:1; /* node is compressed. */ uint32_t size:29; /* number of children, or compressed string len. */ unsigned char data[];
} raxnode; typedef struct rax { raxnode *head; uint64_t numele; uint64_t numnodes;
} rax; typedef struct raxstack { void **stack; /* points to static_items or an heap allocated array. */ size_t items, maxitems; /* number of items contained and total space. */ void *static_items[rax_stack_static_items]; int oom; /* true if pushing into this stack failed for oom at some point. */ } raxstack;
如 redis 源码中的注释所写,rax 进行了一些优化,并不会将一个字符串直接按照每个字符进行树的构建,而是在 insert 有冲突时节点分割处理,在 delete 时如果子节点和父节点都只有一个,则需要进行合并操作。
对于 rax 有兴趣的同学,可以看一下 rax.h、rax.c 的相关代码。
linux radix 树{banned}最佳广泛的用途是用于内存管理,结构 address_space 通过 radix 树跟踪绑定到地址映射上的核心页,该 radix 树允许内存管理代码快速查找标识为 dirty 或 writeback 的页。linux radix 树的 api 函数在 lib/radix-tree.c 中实现。
linux 基数树(radix tree)是将指针与 long 整数键值相关联的机制,它存储有效率,并且可快速查询,用于指针与整数值的映射(如:idr 机制)、内存管理等。
struct radix_tree_node { unsigned int path; unsigned int count; union { struct { struct radix_tree_node *parent; void *private_data;
}; struct rcu_head rcu_head; }; /* for tree user */ struct list_head private_list; void __rcu *slots[radix_tree_map_size]; unsigned long tags[radix_tree_max_tags][radix_tree_tag_longs];
};
关于 linux 内核使用 radix tree 的具体代码,有兴趣的同学可以继续深入。
trie 树在单词搜索、统计、排序等领域有大量的应用。文章从基础概念到具体的脏话过滤的应用、redis 的 rax 和 linux 内核的 radix tree 对 trie 树做了介绍。数据结构和算法是程序高性能的基础,本文抛砖引玉,希望大家对 trie 树有所了解,并在未来开发过程实践和应用 trie 树解决中类似情景的问题。