0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

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

马哥Linux运维 来源:未知 作者:邓佳佳 2018-03-06 17:26 次阅读

前言

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

布隆过滤器 (Bloom Filter)

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

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

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

classBloomfilter(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"""

returnhash(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)

returnself.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是如何运行的:

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

forterm in['dog','fish','cat','bird','duck','emu']:

print'{}: {} {}'.format(term,bf.hash_value(term),bf.might_contain(term))

结果:

[False,False,False,False,True,True,False,False,False,True]

[False,False,False,False,True,True,False,False,False,True]

dog: 5True

fish: 4True

cat: 9True

bird: 9True

duck: 5True

emu: 8False

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

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

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

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

分词

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

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

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]), ...

foridx,ch inenumerate(s):

ifch inmajor_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)

returnresults

主要分割

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

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

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()

foridx,ch inenumerate(s):

ifch inminor_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)

returnresults

次要分割

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

def segments(event):

"""Simple wrapper around major_segments / minor_segments"""

results = set()

formajor inmajor_segments(event):

forminor inminor_segments(major):

results.add(minor)

returnresults

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

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

forterm insegments('src_ip = 1.2.3.4'):

print term

src

1.2

1.2.3.4

src_ip

3

1

1.2.3

ip

2

=

4

搜索

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

上代码:

classSplunk(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

forterm insegments(event):

self.bf.add_value(term)

ifterm notinself.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)

ifnotself.bf.might_contain(term):

return

# In Splunk this probably runs in O(log N) where N is the number of terms in the tsidx

ifterm notinself.terms:

return

forevent_id insorted(self.terms[term]):

yield self.events[event_id]

Splunk代表一个拥有搜索功能的索引集合

每一个集合中包含一个布隆过滤器,一个倒排词表(字典),和一个存储所有事件的数组

当一个事件被加入到索引的时候,会做以下的逻辑

为每一个事件生成一个unqie id,这里就是序号

对事件进行分词,把每一个词加入到倒排词表,也就是每一个词对应的事件的id的映射结构,注意,一个词可能对应多个事件,所以倒排表的的值是一个Set。倒排表是绝大部分搜索引擎的核心功能。

当一个词被搜索的时候,会做以下的逻辑

检查布隆过滤器,如果为假,直接返回

检查词表,如果被搜索单词不在词表中,直接返回

在倒排表中找到所有对应的事件id,然后返回事件的内容

我们运行下看看把:

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')

forevent ins.search('1.2.3.4'):

print event

print'-'

forevent ins.search('src_ip'):

print event

print'-'

forevent ins.search('ip'):

print event

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来实现更复杂的搜索逻辑。

上代码:

classSplunkM(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

forterm insegments(event):

self.bf.add_value(term)

ifterm notinself.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)))

forterm interms:

# If a term isn't present at all then we can stop looking

ifnotself.bf.might_contain(term):

return

ifterm notinself.terms:

return

# Drop events that don't match from our results

results = results.intersection(self.terms[term])

forevent_id insorted(results):

yield self.events[event_id]

def search_any(self,terms):

"""Search for an OR of all terms"""

results = set()

forterm interms:

# If a term isn't present, we skip it, but don't stop

ifnotself.bf.might_contain(term):

continue

ifterm notinself.terms:

continue

# Add these events to our results

results = results.union(self.terms[term])

forevent_id insorted(results):

yield self.events[event_id]

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

运行结果如下:

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')

forevent ins.search_all(['src_ip','5.6']):

print event

print'-'

forevent ins.search_any(['src_ip','dst_ip']):

print event

src_ip = 5.6.7.8

-

src_ip = 1.2.3.4

src_ip = 5.6.7.8

dst_ip = 1.2.3.4

总结

以上的代码只是为了说明大数据搜索的基本原理,包括布隆过滤器,分词和倒排表。如果大家真的想要利用这代码来实现真正的搜索功能,还差的太远。所有的内容来自于Splunk Conf2017。大家如果有兴趣可以去看网上的视频

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • python
    +关注

    关注

    51

    文章

    4675

    浏览量

    83467

原文标题:用 Python 实现一个大数据搜索引擎

文章出处:【微信号:magedu-Linux,微信公众号:马哥Linux运维】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    润和软件与新财富联合发布金融AI对话式搜索引擎“金融搜一搜”产品

    3月29日,新财富投顾嘉年华活动中,江苏润和软件股份有限公司(以下简称“润和软件”)与深圳市新财富数字科技有限责任公司(以下简称“新财富”)联合发布了金融AI对话式搜索引擎——“金融搜一搜”产品,助力金融投资场景智能化升级。
    的头像 发表于 04-02 10:15 112次阅读
    润和软件与新财富联合发布金融AI对话式<b class='flag-5'>搜索引擎</b>“金融搜一搜”产品

    微软向Windows 10/11推送更新,建议将Bing设为Chrome默认搜索引擎

    微软通过提示窗口表示,只要将Bing设为Chrome浏览器的默认搜索引擎,即可免费享用ChatGPT-4,且每天可与Bing人工智能进行数百次的对话交流。
    的头像 发表于 03-15 14:32 477次阅读

    Redis官方搜索引擎来了,性能炸裂!

    RediSearch 是一个 Redis 模块,为 Redis 提供查询、二级索引和全文搜索功能。
    的头像 发表于 02-21 10:01 575次阅读
    Redis官方<b class='flag-5'>搜索引擎</b>来了,性能炸裂!

    生成式AI恐使搜索引擎衰退,预计2026年搜索量将下滑25%

    据市场分析机构Gartner报道,生成式AI对传统搜索引擎构成重大威胁,预计至2026年搜索量将降低25%。为此,企业需调整营销策略。
    的头像 发表于 02-20 10:04 223次阅读

    鸿蒙OS开发之 融合搜索概述

    HarmonyOS 融合搜索为开发者提供搜索引擎级的全文搜索能力,可支持应用内搜索和系统全局搜索,为用户提供更加准确、高效的
    的头像 发表于 01-29 16:24 181次阅读
    鸿蒙OS开发之  融合<b class='flag-5'>搜索</b>概述

    谷歌搜索引擎优化的各个方面和步骤

    谷歌搜索引擎是最受欢迎和广泛使用的搜索引擎之一,为了使你的网站在谷歌上更好地排名并提高曝光度,你可以采取一些谷歌搜索引擎优化的步骤。 使用关键字研究工具,如Google AdWords关键字规划工具
    的头像 发表于 01-25 10:29 299次阅读

    基于BERT算法搭建一个问答搜索引擎

    学习的新手发现BERT模型并不好搭建,上手难度很高,普通人可能要研究几天才能勉强搭建出一个模型。 没关系,今天我们介绍的这个模块,能让你在3分钟内基于BERT算法搭建一个问答搜索引擎。它就是 bert-as-service 项目。这个开源项目,能够让你基于多GPU机器快速搭建BERT服务(支持微
    的头像 发表于 10-30 11:46 342次阅读
    基于BERT算法搭建一个问答<b class='flag-5'>搜索引擎</b>

    网络爬虫 Python数据分析

    网络爬虫是自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成。传统爬虫从
    发表于 09-25 08:25

    FPGA加速视觉搜索引擎解决方案

    电子发烧友网站提供《FPGA加速视觉搜索引擎解决方案.pdf》资料免费下载
    发表于 09-13 10:32 1次下载
    FPGA加速视觉<b class='flag-5'>搜索引擎</b>解决方案

    百度、英伟达联合举办搜索创新大赛 搜索引擎变革 搜索+AI

    近日,百度文心一言宣布向全社会开放,首日,百度搜索就有超3亿次需求由生成式智能引擎解决;百度搜索“AI伙伴”当日访问用户数突破400万。 在这样的背景下,9月7日,以“新搜索·新奇点”
    的头像 发表于 09-07 19:32 721次阅读

    NVIDIA Ampere 架构的结构化稀疏功能及其在搜索引擎中的应用

    NVIDIA Ampere 架构的结构化稀疏功能 及其在搜索引擎中的应用 深度学习彻底改变了我们分析、理解和处理数据的方式,而且在各个领域的应用中都取得了巨大的成功,其在计算机视觉、自然语言处理
    的头像 发表于 07-18 17:45 307次阅读
    NVIDIA Ampere 架构的结构化稀疏功能及其在<b class='flag-5'>搜索引擎</b>中的应用

    Neeva宣布关闭其搜索引擎

    但打造搜索引擎实际上是很容易的部分。Ramaswamy和Raghunathan继续说道:“在整个过程中,我们发现打造搜索引擎是一回事,而说服普通用户需要转向更好的选择则是另一回事。”
    的头像 发表于 05-24 10:22 490次阅读

    使用Rust语言重写的代码搜索引擎黑鸟系统Blackbird正式启用

    其次,需要完全从头开始构建了一个新的代码搜索引擎。新的引擎需要非常快(大约是旧代码搜索速度的两倍),功能更强大(支持子字符串查询、正则表达式和符号搜索),并且理解代码,将最相关的结果放
    的头像 发表于 05-11 09:52 505次阅读
    使用Rust语言重写的代码<b class='flag-5'>搜索引擎</b>黑鸟系统Blackbird正式启用

    每当连接到WI-FI时给我code6,无法在搜索引擎中输入它怎么了?

    每当连接到 WI-FI 时给我 code6 嗨,我无法在搜索引擎中输入它!怎么了?
    发表于 05-10 11:01

    微软GPT-4搜索引擎重大升级 新Bing开放AI能力

    微软GPT-4搜索引擎重大升级 新Bing开放AI能力 微软和OpenAI合作将人工智能技术应用于必应搜索带来了更多不一样的搜索体验。 此前Open AI发布了新一代大型人工智能语言训练模型
    的头像 发表于 05-05 17:15 2239次阅读