基于Python语言的大数据搜索引擎

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

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

[[270206]]

布隆过滤器 (Bloom Filter)

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

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

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

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

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

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

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

结果:

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

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

基于python语言的大数据搜索引擎

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

基于python语言的大数据搜索引擎

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

基于python语言的大数据搜索引擎

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

基于python语言的大数据搜索引擎

分词

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

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

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

主要分割

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

  • ] < > ( ) { } | ! ; , ' " * s & ? + %21 %26 %2526 %3B %7C %20 %2B %3D -- %2520 %5D %5B %3A %0A %2C %28 %29
  1. def minor_segments(s): 
  2.  ""
  3.  Perform minor segmenting on a string. This is like major 
  4.  segmenting, except it also captures from the start of the 
  5.  input to each break. 
  6.  ""
  7.  minor_breaks = '_.' 
  8.  last = -1 
  9.  results = set() 
  10.  for idx, ch in enumerate(s): 
  11.  if ch in minor_breaks: 
  12.  segment = s[last+1:idx] 
  13.  results.add(segment) 
  14.  segment = s[:idx] 
  15.  results.add(segment) 
  16.  last = idx 
  17.  segment = s[last+1:] 
  18.  results.add(segment) 
  19.  results.add(s) 
  20.  return results 

次要分割

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

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

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

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

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

搜索

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

上代码:

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

我们运行下看看把:

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

是不是很赞!

更复杂的搜索

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

上代码:

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

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

运行结果如下:

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

总结

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

责任编辑:未丽燕 来源: 今日头条
相关推荐

2010-03-11 19:06:52

Python编程语言

2011-06-20 18:23:06

SEO

2017-11-27 13:39:29

Python大数据搜索引擎

2014-06-23 15:12:29

大数据

2018-07-05 22:38:23

大数据搜索引擎SEO

2009-02-19 09:41:36

搜索引擎搜狐百度

2009-09-22 16:23:52

搜索引擎

2020-03-20 10:14:49

搜索引擎倒排索引

2017-08-07 08:15:31

搜索引擎倒排

2016-08-18 00:54:59

Python图片处理搜索引擎

2016-12-26 13:41:19

大数据搜索引擎工作原理

2010-04-20 11:43:46

2010-06-13 16:27:28

搜索引擎

2012-09-07 13:22:21

搜索搜狗

2022-10-08 09:13:18

搜索引擎⽹站

2012-12-06 14:45:59

2015-08-04 10:50:03

大数据时代搜索引擎

2011-06-22 17:28:51

SEO

2020-08-10 14:39:30

搜索引擎

2012-05-14 11:01:50

搜索引擎微软
点赞
收藏

51CTO技术栈公众号