【问题标题】:Retrieve IP address data from mongodb in pymongo using regular expression or pattern matching使用正则表达式或模式匹配从 pymongo 中的 mongodb 检索 IP 地址数据
【发布时间】:2015-08-02 04:31:01
【问题描述】:

我正在使用 mongodb 来存储我的数据,并且我习惯于遵循 python 脚本来执行查询以查找集合的计数,

collection_name = "prodresultlistCollection_%s_%s" %(sys.argv[1], sys.argv[2])
my_collection = mydb[collection_name]

parameter = "IP addr"
ip = "10.20.30.40"
count1 = my_collection.count({ '$and': [{parameter:'%s' %(ip)}]})

这里的count1 显示了具有给定ip 值的行数。此count1 查询仅计算ip == IP addr 所在的行数。但在数据库中IP addr属性可以有一个或多个IP,格式如下,

10.20.30.40
10.20.30.40,20.35.45.55
10.20.30.40,20.35.45.55,10.10.10.10
etc...

假设数据库中的IP addr 值为10.20.30.40,20.35.45.55,那么无论给定查询的ip 模式如何,都应检索该行。

ip = 10
ip = 10.20
ip = 10.20.30
ip = 10.20.30.40
ip = 20
ip = 20.35
ip = 20.35.45
ip = 20.35.45.55

count1 查询的上述所有ip 情况下,应检索数据库中IP addr 值为10.20.30.40,20.35.45.55 的特定行。我尝试使用下面给出的正则表达式来解决问题,但它在 pymongo 中显示语法错误,并且在某些情况下没有检索到任何行。

count1 = my_collection.count({ '$and': [{parameter:/'%s'/ %(ip)}]})
count1 = my_collection.count({ '$and': [{parameter:'/%s/' %(ip)}]})
count1 = my_collection.count({ '$and': [{parameter:/%s/ %(ip)}]})

然后我尝试使用下面的代码使用正则表达式匹配 IP 模式:

import re

IP = raw_input("Enter the IP: ")
S = IP.split(".")
IP_DB = "10.20.30.40,20.35.45.55"

if len(S)==4:
    obj = re.search(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",IP_DB)
elif len(S)==3:
    obj = re.search(r"^\d{1,3}\.\d{1,3}\.\d{1,3}",IP_DB)
elif len(S)==2:
    obj = re.search(r"^\d{1,3}\.\d{1,3}",IP_DB)
elif len(S)==1:
    obj = re.search(r"^\d{1,3}",IP_DB)
else:
    print "Invalid IP!!!"

if obj:
    print obj.group()
else:
    print "Nothing found!!!"

但这里的问题是,它只比较 IP 的模式而不是值。对于模式xx.xx.xx.xx 中给出的任何IP 值,此代码返回true 以获取匹配/搜索结果。此处也不考虑 IP 的第二部分。有没有更好的方法来解决这个问题?我需要使用 ip 从 mongodb 数据库中检索行,以使给定的 ip 的任何模式与数据库中的 IP addr 匹配。应该在count1 查询中给出什么样的语法或正则表达式来实现这一点?

【问题讨论】:

    标签: python regex mongodb ip database


    【解决方案1】:

    作为regex 模式,pymongo 接受常规的Python regex object。因此,您可以执行以下操作:

    import re
    
    regex = re.compile('{}'.format(YOUR_IP_ADDR))
    
    count = my_collection.find({'ip_addr_field': regex}).count()
    

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 2011-08-27
      • 1970-01-01
      • 2012-04-27
      • 2011-08-17
      • 2011-03-01
      • 1970-01-01
      • 2010-09-11
      相关资源
      最近更新 更多