搜索是大数据领域里常见的需求。Splunk和ELK分别是该领域在非开源和开源领域里的领导者。本文利用很少的Python代码实现了一个基本的数据搜索功能,试图让大家理解大数据搜索的基本原理。

布隆过滤器 (Bloom Filter)

第一步我们先要实现一个布隆过滤器

布隆过滤器是大数据领域的一个常见算法,它的目的是过滤掉那些不是目标的元素。也就是说如果一个要搜索的词并不存在与我的数据中,那么它可以以很快的速度返回目标不存在。

让我们看看以下布隆过滤器的代码:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Bloomfilter(object):
    """
    A Bloom filter is a probabilistic data-structure that trades space for accuracy
    when determining if a value is in a set.  It can tell you if a value was possibly
    added, or if it was definitely not added, but it can't tell you for certain that
    it was added.
    """
    def __init__(self, size):
        """Setup the BF with the appropriate size"""
        self.values = [False] * size
        self.size = size
 
    def hash_value(self, value):
        """Hash the value provided and scale it to fit the BF size"""
        return hash(value) % self.size
 
    def add_value(self, value):
        """Add a value to the BF"""
        h = self.hash_value(value)
        self.values[h] = True
 
    def might_contain(self, value):
        """Check if the value might be in the BF"""
        h = self.hash_value(value)
        return self.values[h]
 
    def print_contents(self):
        """Dump the contents of the BF for debugging purposes"""
        print self.values
  • 基本的数据结构是个数组(实际上是个位图,用1/0来记录数据是否存在),初始化是没有任何内容,所以全部置False。实际的使用当中,该数组的长度是非常大的,以保证效率。
  • 利用哈希算法来决定数据应该存在哪一位,也就是数组的索引
  • 当一个数据被加入到布隆过滤器的时候,计算它的哈希值然后把相应的位置为True
  • 当检查一个数据是否已经存在或者说被索引过的时候,只要检查对应的哈希值所在的位的True/Fasle

看到这里,大家应该可以看出,如果布隆过滤器返回False,那么数据一定是没有索引过的,然而如果返回True,那也不能说数据一定就已经被索引过。在搜索过程中使用布隆过滤器可以使得很多没有命中的搜索提前返回来提高效率。

我们看看这段 code是如何运行的:

 
 
1
2
3
4
5
6
7
8
9
10
bf = Bloomfilter(10)
bf.add_value('dog')
bf.add_value('fish')
bf.add_value('cat')
bf.print_contents()
bf.add_value('bird')
bf.print_contents()
# Note: contents are unchanged after adding bird - it collides
for term in ['dog', 'fish', 'cat', 'bird', 'duck', 'emu']:
    print '{}: {} {}'.format(term, bf.hash_value(term), bf.might_contain(term))

结果:

 
 
1
2
3
4
5
6
7
8
[False, False, False, False, True, True, False, False, False, True]
[False, False, False, False, True, True, False, False, False, True]
dog: 5 True
fish: 4 True
cat: 9 True
bird: 9 True
duck: 5 True
emu: 8 False

首先创建了一个容量为10的的布隆过滤器

然后分别加入 ‘dog’,‘fish’,‘cat’三个对象,这时的布隆过滤器的内容如下:

然后加入‘bird’对象,布隆过滤器的内容并没有改变,因为‘bird’和‘fish’恰好拥有相同的哈希。

最后我们检查一堆对象(’dog’, ‘fish’, ‘cat’, ‘bird’, ‘duck’, ’emu’)是不是已经被索引了。结果发现‘duck’返回True,2而‘emu’返回False。因为‘duck’的哈希恰好和‘dog’是一样的。

分词

下面一步我们要实现分词。 分词的目的是要把我们的文本数据分割成可搜索的最小单元,也就是词。这里我们主要针对英语,因为中文的分词涉及到自然语言处理,比较复杂,而英文基本只要用标点符号就好了。

下面我们看看分词的代码:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def major_segments(s):
    """
    Perform major segmenting on a string.  Split the string by all of the major
    breaks, and return the set of everything found.  The breaks in this implementation
    are single characters, but in Splunk proper they can be multiple characters.
    A set is used because ordering doesn't matter, and duplicates are bad.
    """
    major_breaks = ' '
    last = -1
    results = set()
 
    # enumerate() will give us (0, s[0]), (1, s[1]), ...
    for idx, ch in enumerate(s):
        if ch in major_breaks:
            segment = s[last+1:idx]
            results.add(segment)
 
            last = idx
 
    # The last character may not be a break so always capture
    # the last segment (which may end up being "", but yolo)    
    segment = s[last+1:]
    results.add(segment)
 
    return results

主要分割

主要分割使用空格来分词,实际的分词逻辑中,还会有其它的分隔符。例如Splunk的缺省分割符包括以下这些,用户也可以定义自己的分割符。

] < >( ) { } | ! ; , ‘ ” * \n \r \s \t & ? + %21 %26 %2526 %3B %7C %20 %2B %3D — %2520 %5D %5B %3A %0A %2C %28 %29

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def minor_segments(s):
    """
    Perform minor segmenting on a string.  This is like major
    segmenting, except it also captures from the start of the
    input to each break.
    """
    minor_breaks = '_.'
    last = -1
    results = set()
 
    for idx, ch in enumerate(s):
        if ch in minor_breaks:
            segment = s[last+1:idx]
            results.add(segment)
 
            segment = s[:idx]
            results.add(segment)
 
            last = idx
 
    segment = s[last+1:]
    results.add(segment)
    results.add(s)
 
    return results

次要分割

次要分割和主要分割的逻辑类似,只是还会把从开始部分到当前分割的结果加入。例如“1.2.3.4”的次要分割会有1,2,3,4,1.2,1.2.3

 
 
1
2
3
4
5
6
7
def segments(event):
    """Simple wrapper around major_segments / minor_segments"""
    results = set()
    for major in major_segments(event):
        for minor in minor_segments(major):
            results.add(minor)
    return results

分词的逻辑就是对文本先进行主要分割,对每一个主要分割在进行次要分割。然后把所有分出来的词返回。

我们看看这段 code是如何运行的:

 
 
1
2
for term in segments('src_ip = 1.2.3.4'):
        print term
 
 
1
2
3
4
5
6
7
8
9
10
11
src
1.2
1.2.3.4
src_ip
3
1
1.2.3
ip
2
=
4

搜索

好了,有个分词和布隆过滤器这两个利器的支撑后,我们就可以来实现搜索的功能了。

上代码:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Splunk(object):
    def __init__(self):
        self.bf = Bloomfilter(64)
        self.terms = {}  # Dictionary of term to set of events
        self.events = []
    
    def add_event(self, event):
        """Adds an event to this object"""
 
        # Generate a unique ID for the event, and save it
        event_id = len(self.events)
        self.events.append(event)
 
        # Add each term to the bloomfilter, and track the event by each term
        for term in segments(event):
            self.bf.add_value(term)
 
            if term not in self.terms:
                self.terms[term] = set()
            self.terms[term].add(event_id)
 
    def search(self, term):
        """Search for a single term, and yield all the events that contain it"""
        
        # In Splunk this runs in O(1), and is likely to be in filesystem cache (memory)
        if not self.bf.might_contain(term):
            return
 
        # In Splunk this probably runs in O(log N) where N is the number of terms in the tsidx
        if term not in self.terms:
            return
 
        for event_id in sorted(self.terms[term]):
            yield self.events[event_id]
  • Splunk代表一个拥有搜索功能的索引集合
  • 每一个集合中包含一个布隆过滤器,一个倒排词表(字典),和一个存储所有事件的数组
  • 当一个事件被加入到索引的时候,会做以下的逻辑
    • 为每一个事件生成一个unqie id,这里就是序号
    • 对事件进行分词,把每一个词加入到倒排词表,也就是每一个词对应的事件的id的映射结构,注意,一个词可能对应多个事件,所以倒排表的的值是一个Set。倒排表是绝大部分搜索引擎的核心功能。
  • 当一个词被搜索的时候,会做以下的逻辑
    • 检查布隆过滤器,如果为假,直接返回
    • 检查词表,如果被搜索单词不在词表中,直接返回
    • 在倒排表中找到所有对应的事件id,然后返回事件的内容

我们运行下看看把:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
s = Splunk()
s.add_event('src_ip = 1.2.3.4')
s.add_event('src_ip = 5.6.7.8')
s.add_event('dst_ip = 1.2.3.4')
 
for event in s.search('1.2.3.4'):
    print event
print '-'
for event in s.search('src_ip'):
    print event
print '-'
for event in s.search('ip'):
    print event
 
 
1
2
3
4
5
6
7
8
9
src_ip = 1.2.3.4
dst_ip = 1.2.3.4
-
src_ip = 1.2.3.4
src_ip = 5.6.7.8
-
src_ip = 1.2.3.4
src_ip = 5.6.7.8
dst_ip = 1.2.3.4

是不是很赞!

更复杂的搜索

更进一步,在搜索过程中,我们想用And和Or来实现更复杂的搜索逻辑。

上代码:

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class SplunkM(object):
    def __init__(self):
        self.bf = Bloomfilter(64)
        self.terms = {}  # Dictionary of term to set of events
        self.events = []
    
    def add_event(self, event):
        """Adds an event to this object"""
 
        # Generate a unique ID for the event, and save it
        event_id = len(self.events)
        self.events.append(event)
 
        # Add each term to the bloomfilter, and track the event by each term
        for term in segments(event):
            self.bf.add_value(term)
            if term not in self.terms:
                self.terms[term] = set()
            
            self.terms[term].add(event_id)
 
    def search_all(self, terms):
        """Search for an AND of all terms"""
 
        # Start with the universe of all events...
        results = set(range(len(self.events)))
 
        for term in terms:
            # If a term isn't present at all then we can stop looking
            if not self.bf.might_contain(term):
                return
            if term not in self.terms:
                return
 
            # Drop events that don't match from our results
            results = results.intersection(self.terms[term])
 
        for event_id in sorted(results):
            yield self.events[event_id]
 
 
    def search_any(self, terms):
        """Search for an OR of all terms"""
        results = set()
 
        for term in terms:
            # If a term isn't present, we skip it, but don't stop
            if not self.bf.might_contain(term):
                continue
            if term not in self.terms:
                continue
 
            # Add these events to our results
            results = results.union(self.terms[term])
 
        for event_id in sorted(results):
            yield self.events[event_id]

利用Python集合的intersection和union操作,可以很方便的支持And(求交集)和Or(求合集)的操作。

运行结果如下:

 
 
1
2
3
4
5
6
7
8
9
10
s = SplunkM()
s.add_event('src_ip = 1.2.3.4')
s.add_event('src_ip = 5.6.7.8')
s.add_event('dst_ip = 1.2.3.4')
 
for event in s.search_all(['src_ip', '5.6']):
    print event
print '-'
for event in s.search_any(['src_ip', 'dst_ip']):
    print event
 
 
1
2
3
4
5
src_ip = 5.6.7.8
-
src_ip = 1.2.3.4
src_ip = 5.6.7.8
dst_ip = 1.2.3.4

总结

以上的代码只是为了说明大数据搜索的基本原理,包括布隆过滤器,分词和倒排表。如果大家真的想要利用这代码来实现真正的搜索功能,还差的太远

用 Python 实现一个大数据搜索引擎的更多相关文章

  1. 用Python实现一个大数据搜索引擎

    用Python实现一个大数据搜索引擎 搜索是大数据领域里常见的需求.Splunk和ELK分别是该领域在非开源和开源领域里的领导者.本文利用很少的Python代码实现了一个基本的数据搜索功能,试图让大家 ...

  2. 如何基于Go搭建一个大数据平台

    如何基于Go搭建一个大数据平台 - Go中国 - CSDN博客 https://blog.csdn.net/ra681t58cjxsgckj31/article/details/78333775 01 ...

  3. 零起点PYTHON足彩大数据与机器学习实盘分析

    零起点PYTHON足彩大数据与机器学习实盘分析 第1章 足彩与数据分析 1 1.1 “阿尔法狗”与足彩 1 1.2 案例1-1:可怕的英国足球 3 1.3 关于足彩的几个误区 7 1.4 足彩·大事件 ...

  4. 我的ElasticSearch集群部署总结--大数据搜索引擎你不得不知

    摘要:世上有三类书籍:1.介绍知识,2.阐述理论,3.工具书:世间也存在两类知识:1.技术,2.思想.以下是我在部署ElasticSearch集群时的经验总结,它们大体属于第一类知识“techknow ...

  5. 如何做一个大数据seo人员

    作为流量运营者或者SEO人员,对于所从事行业领域的认识往往建立在一种直觉之上,我们很难对一个行业有一个全面的了解,这个行业领域有多宽,流量聚焦在哪里,那些是用户最关心的问题? 有的时候很难准确的把握, ...

  6. 一个大数据平台省了20个IT人力——敦奴数据平台建设案例分享

    认识敦奴 敦奴集团创立于1987年,主营服装.酒店.地产,总部位于中国皮都-海宁.浙江敦奴联合实业股份有限公司(以下简称"敦奴")是一家集开发.设计.生产.销售于一体的大型专业服装 ...

  7. 一个大数据的demo

    package test.admin; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Fil ...

  8. 大数据搜索引擎之elasticsearch使用篇(一)

    作者:yanzm 原文来自:https://bbs.ichunqiu.com/thread-42421-1-1.html 1.基础介绍 本期,我们将着重介绍elasticsearch的基本使用方法. ...

  9. 一个大数据方案:基于Nutch+Hadoop+Hbase+ElasticSearch的网络爬虫及搜索引擎

    网络爬虫架构在Nutch+Hadoop之上,是一个典型的分布式离线批量处理架构,有非常优异的吞吐量和抓取性能并提供了大量的配置定制选项.由于网络爬虫只负责网络资源的抓取,所以,需要一个分布式搜索引擎, ...

随机推荐

  1. 20155212 2016-2017-2《Java程序设计》课程总结

    每周博客 每周作业链接汇总 预备作业一:专业理解.未来展望.期望的师生关系. 预备作业二:HOMEWORK-2 预备作业三:HOMEWORK-3 第一周作业:学习教材Chapter 1 Java平台概 ...

  2. mogodb的安装与配置

    下载:https://www.mongodb.com/https://www.mongodb.com/ 安装:一直next,中间选择custom,选择自己的安装路径,最后安装成功. 配置:打开安装好的 ...

  3. linux 配置免密码登陆

    在使用scp命令传输的时候需要密码 配置免密码登陆 ssh-keygen -t rsa (四个回车) 执行命令完成后,会生成两个文件id_rsa(私钥).id-rsa.pub(公钥) 将公钥拷贝到要免 ...

  4. required_new spring事务传播行为无效碰到的坑!

    在测试事务传播行为的时候,因为用了同一个service中的方法测试,所以不管怎么设置都无效了: 原因是aop动态代理只会拦截一次执行方法,第二个方法是照搬的,只要调用其他service中的事务方法,传 ...

  5. go 数组

    数组的定义和 初始化 数组是同一类型的元素集合 ]int //定义⼀个数组 Go中数组下标从0开始,因此长度为n的数组下标范围:[0,n-1] 整数数组中的元素默认初始化为0,字符串数组中的元素默认初 ...

  6. C 语言问题

    1.  如何生成 "半全局变量", 就是那种只能被部分源文件中的部分函数访问变量? 答: 这在C语言中办不到. 如果不能或不方便在一个源文件中放下所有的函数, 那么有三种的解决方案 ...

  7. mac 升级10.12 php debug 环境 跑不起的解决 解决方案

    1:  mac 升级后发现 php从原来的5.5  升级为 5.6 了...   所以以前 php.ini 里面的配置全部都没有了. mac 给我们做了备份2:  没办法只能升级php对应的插件到5. ...

  8. git —— 分支

    git中每一个分支相当于一个时间线 并列且相互平行 控制用指针控制~ 1.第一种创建命令: $ git branch 分支名称 —— 创建分支 $ git checkout 分支名称 —— 切换分支 ...

  9. 洛谷P1938 找工就业

    传送门啦 这个题本质就是跑一边最长路,重点就是在怎么建图上. 我们可以把点权放到边权上面,即将每一个边的终点点权当做这个边的边权,这个题里就是将工钱 $ d $ 当做边权. 如果这一条边需要坐飞机才能 ...

  10. 使用html+css+js实现魔性的舞蹈

    使用html+css+js实现魔性的舞蹈,让我们燥起来!!! 效果图: 代码如下,复制代码即可使用: <!DOCTYPE html> <html > <head> ...