最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談用Python實現(xiàn)一個大數(shù)據(jù)搜索引擎

 更新時間:2017年11月28日 10:41:01   作者:naughty  
這篇文章主要介紹了淺談用Python實現(xiàn)一個大數(shù)據(jù)搜索引擎,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

搜索是大數(shù)據(jù)領(lǐng)域里常見的需求。Splunk和ELK分別是該領(lǐng)域在非開源和開源領(lǐng)域里的領(lǐng)導(dǎo)者。本文利用很少的Python代碼實現(xiàn)了一個基本的數(shù)據(jù)搜索功能,試圖讓大家理解大數(shù)據(jù)搜索的基本原理。

布隆過濾器 (Bloom Filter)

第一步我們先要實現(xiàn)一個布隆過濾器。

布隆過濾器是大數(shù)據(jù)領(lǐng)域的一個常見算法,它的目的是過濾掉那些不是目標(biāo)的元素。也就是說如果一個要搜索的詞并不存在與我的數(shù)據(jù)中,那么它可以以很快的速度返回目標(biāo)不存在。

讓我們看看以下布隆過濾器的代碼:

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. 基本的數(shù)據(jù)結(jié)構(gòu)是個數(shù)組(實際上是個位圖,用1/0來記錄數(shù)據(jù)是否存在),初始化是沒有任何內(nèi)容,所以全部置False。實際的使用當(dāng)中,該數(shù)組的長度是非常大的,以保證效率。
  2. 利用哈希算法來決定數(shù)據(jù)應(yīng)該存在哪一位,也就是數(shù)組的索引
  3. 當(dāng)一個數(shù)據(jù)被加入到布隆過濾器的時候,計算它的哈希值然后把相應(yīng)的位置為True
  4. 當(dāng)檢查一個數(shù)據(jù)是否已經(jīng)存在或者說被索引過的時候,只要檢查對應(yīng)的哈希值所在的位的True/Fasle

看到這里,大家應(yīng)該可以看出,如果布隆過濾器返回False,那么數(shù)據(jù)一定是沒有索引過的,然而如果返回True,那也不能說數(shù)據(jù)一定就已經(jīng)被索引過。在搜索過程中使用布隆過濾器可以使得很多沒有命中的搜索提前返回來提高效率。

我們看看這段 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
for term in ['dog', 'fish', 'cat', 'bird', 'duck', 'emu']:
  print '{}: {} {}'.format(term, bf.hash_value(term), bf.might_contain(term))

結(jié)果:

[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

首先創(chuàng)建了一個容量為10的的布隆過濾器

然后分別加入 ‘dog',‘fish',‘cat'三個對象,這時的布隆過濾器的內(nèi)容如下:

然后加入‘bird'對象,布隆過濾器的內(nèi)容并沒有改變,因為‘bird'和‘fish'恰好擁有相同的哈希。

最后我們檢查一堆對象('dog', 'fish', 'cat', 'bird', 'duck', 'emu')是不是已經(jīng)被索引了。結(jié)果發(fā)現(xiàn)‘duck'返回True,2而‘emu'返回False。因為‘duck'的哈希恰好和‘dog'是一樣的。

分詞

下面一步我們要實現(xiàn)分詞。 分詞的目的是要把我們的文本數(shù)據(jù)分割成可搜索的最小單元,也就是詞。這里我們主要針對英語,因為中文的分詞涉及到自然語言處理,比較復(fù)雜,而英文基本只要用標(biāo)點符號就好了。

下面我們看看分詞的代碼:

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

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

次要分割

次要分割和主要分割的邏輯類似,只是還會把從開始部分到當(dāng)前分割的結(jié)果加入。例如“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()
  for major in major_segments(event):
    for minor in minor_segments(major):
      results.add(minor)
  return results

分詞的邏輯就是對文本先進(jìn)行主要分割,對每一個主要分割在進(jìn)行次要分割。然后把所有分出來的詞返回。

我們看看這段 code是如何運行的:

for term in segments('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

搜索

好了,有個分詞和布隆過濾器這兩個利器的支撐后,我們就可以來實現(xiàn)搜索的功能了。

上代碼:

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代表一個擁有搜索功能的索引集合

每一個集合中包含一個布隆過濾器,一個倒排詞表(字典),和一個存儲所有事件的數(shù)組

當(dāng)一個事件被加入到索引的時候,會做以下的邏輯

  1. 為每一個事件生成一個unqie id,這里就是序號
  2. 對事件進(jìn)行分詞,把每一個詞加入到倒排詞表,也就是每一個詞對應(yīng)的事件的id的映射結(jié)構(gòu),注意,一個詞可能對應(yīng)多個事件,所以倒排表的的值是一個Set。倒排表是絕大部分搜索引擎的核心功能。

當(dāng)一個詞被搜索的時候,會做以下的邏輯

  1. 檢查布隆過濾器,如果為假,直接返回
  2. 檢查詞表,如果被搜索單詞不在詞表中,直接返回
  3. 在倒排表中找到所有對應(yīng)的事件id,然后返回事件的內(nèi)容

我們運行下看看把:

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

是不是很贊!

更復(fù)雜的搜索

更進(jìn)一步,在搜索過程中,我們想用And和Or來實現(xiàn)更復(fù)雜的搜索邏輯。

上代碼:

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(求合集)的操作。

運行結(jié)果如下:

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
src_ip = 5.6.7.8
-
src_ip = 1.2.3.4
src_ip = 5.6.7.8
dst_ip = 1.2.3.4

總結(jié)

以上的代碼只是為了說明大數(shù)據(jù)搜索的基本原理,包括布隆過濾器,分詞和倒排表。如果大家真的想要利用這代碼來實現(xiàn)真正的搜索功能,還差的太遠(yuǎn)。所有的內(nèi)容來自于Splunk Conf2017。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python實現(xiàn)與arduino的串口通信的示例代碼

    python實現(xiàn)與arduino的串口通信的示例代碼

    本文主要介紹了python實現(xiàn)與arduino的串口通信的示例代碼, 在Python中,我們可以使用pyserial庫來實現(xiàn)與Arduino的串口通信,下面就來介紹一下如何使用,感興趣的可以了解一下
    2024-01-01
  • Python基礎(chǔ)教程之異常詳解

    Python基礎(chǔ)教程之異常詳解

    調(diào)試Python程序時,經(jīng)常會報出一些異常,下面這篇文章就來給大家介紹了關(guān)于Python基礎(chǔ)教程之異常的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2019-01-01
  • 用python 繪制莖葉圖和復(fù)合餅圖

    用python 繪制莖葉圖和復(fù)合餅圖

    這篇文章主要介紹了用python 繪制莖葉圖和復(fù)合餅圖,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-02-02
  • OpenCV實戰(zhàn)之實現(xiàn)手勢虛擬縮放效果

    OpenCV實戰(zhàn)之實現(xiàn)手勢虛擬縮放效果

    本篇將會以HandTrackingModule為模塊,實現(xiàn)通過手勢對本人的博客海報進(jìn)行縮放。文中的示例代碼講解詳細(xì),具有一定的借鑒價值,需要的可以參考一下
    2022-11-11
  • Python使用pyttsx3實現(xiàn)文本朗讀功能的詳細(xì)教程及避坑指南

    Python使用pyttsx3實現(xiàn)文本朗讀功能的詳細(xì)教程及避坑指南

    今天給大家?guī)硪粋€非常實用的Python庫——pyttsx3,它可以把文字轉(zhuǎn)換成語音,讓你的程序開口說話,這篇文章會從零開始,一步步教你搭建環(huán)境、編寫代碼,并分享一些踩坑經(jīng)驗,需要的朋友可以參考下
    2026-03-03
  • Python爬蟲簡單運用爬取代理IP的實現(xiàn)

    Python爬蟲簡單運用爬取代理IP的實現(xiàn)

    這篇文章主要介紹了Python爬蟲簡單運用爬取代理IP的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • scrapy結(jié)合selenium解析動態(tài)頁面的實現(xiàn)

    scrapy結(jié)合selenium解析動態(tài)頁面的實現(xiàn)

    這篇文章主要介紹了scrapy結(jié)合selenium解析動態(tài)頁面的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • python中比較兩個列表的實例方法

    python中比較兩個列表的實例方法

    在本篇文章里小編給各位分享了關(guān)于python中比較兩個列表的實例方法以及相關(guān)代碼,需要的朋友們參考下。
    2019-07-07
  • 詳解Django中CBV(Class Base Views)模型源碼分析

    詳解Django中CBV(Class Base Views)模型源碼分析

    這篇文章主要介紹了詳解Django中CBV(Class Base Views)模型源碼分析,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • Python中的列表生成式與生成器學(xué)習(xí)教程

    Python中的列表生成式與生成器學(xué)習(xí)教程

    這篇文章主要介紹了Python中的列表生成式與生成器學(xué)習(xí)教程,Python中的Generator生成器比列表生成式功能更為強大,需要的朋友可以參考下
    2016-03-03

最新評論

卓资县| 永善县| 西和县| 桦南县| 抚顺市| 东明县| 南和县| 顺义区| 韶关市| 景东| 齐河县| 墨玉县| 公主岭市| 抚宁县| 林西县| 调兵山市| 郴州市| 岳池县| 南皮县| 永泰县| 乐安县| 大埔区| 呼图壁县| 淅川县| 万载县| 枣庄市| 来宾市| 山东省| 湘潭市| 甘南县| 松桃| 砚山县| 山阳县| 马龙县| 两当县| 绍兴市| 札达县| 灌阳县| 吐鲁番市| 永春县| 安西县|