Home  >  Article  >  Database  >  小计-python调用pymongo模糊正则查询的方法

小计-python调用pymongo模糊正则查询的方法

WBOY
WBOYOriginal
2016-06-07 16:41:041386browse

这边的数据平台,有个操作是通过关键字得出相关的项目,以前的写法是精确的匹配,这个很让人恼火,毕竟不是谁都可以记住完整的关键字和项目名称,这个着实让人闹心。 mongodb shell模式的模糊查询是用,db.project.find({name:/xiaorui.cc/}) 。 在pymongodb

这边的数据平台,有个操作是通过关键字得出相关的项目,以前的写法是精确的匹配,这个很让人恼火,毕竟不是谁都可以记住完整的关键字和项目名称,这个着实让人闹心。 


mongodb shell模式的模糊查询是用,db.project.find({‘name’:/xiaorui.cc/}) 。   在pymongodb里面肯定不能是这个样子了。  我原以为和pymongo差不多,最后总是出错,最后看了下文档,才解决的问题。 

db.project.find({'name':/汽车/})
{ "_id" : 139, "black_list" : [ ], "created_on" : ISODate("2014-10-08T15:09:41.560Z"), "effective_time" : [ 1412697600, 1412697600 ], "industry_id" : 1000, "name" : "爱卡汽车", "regex" : 0, "status" : 0, "topic_ids" : [ 	2007, 	2008, 	2009, 	2010, 	2011, 	2012, 	2013, 	2014, 	2015, 	2016, 	2017, 	2018, 	2019, 	2020, 	2021, 	2022, 	2023, 	2024, 	2025, 	2026, 	2027, 	2028, 	2029, 	2030, 	2031, 	2032 ], "user_id" : 44, "white_list" : [ ] }

下面是python使用pymongo来的正则模糊查询方式。 两种,一个是mongo自带的扩展,regex,另一个是可以嵌入import re模块来操作。 

注释:

老规矩,原文地址是 blog.xiaorui.cc … 爬虫,fuck !

In [76]: a
Out[76]: '\xe6\xb1\xbd\xe8\xbd\xa6'
In [77]: print a
汽车
In [78]: list(db.project.find({'name':{'$regex':a}}))
Out[78]:
[{u'_id': 139,
  u'black_list': [],
  u'created_on': datetime.datetime(2014, 10, 8, 15, 9, 41, 560000),
  u'effective_time': [1412697600, 1412697600],
  u'industry_id': 1000,
  u'name': u'\u7231\u5361\u6c7d\u8f66',
  u'regex': 0,
  u'status': 0,
  u'topic_ids': [2007,
   2008,
   2009,
   2010,
   2011,
   2012,
   2013,
   2014,
   2015,
   2016,
   2017,
   2018,
   2019,
   2020,
   2021,
   2022,
   2023,
   2024,
   2025,
   2026,
   2027,
   2028,
   2029,
   2030,
   2031,
   2032],
  u'user_id': 44,
  u'white_list': []}]
In [79]: list(db.project.find({'name':re.compile(a)}))
Out[79]:
[{u'_id': 139,
  u'black_list': [],
  u'created_on': datetime.datetime(2014, 10, 8, 15, 9, 41, 560000),
  u'effective_time': [1412697600, 1412697600],
  u'industry_id': 1000,
  u'name': u'\u7231\u5361\u6c7d\u8f66',
  u'regex': 0,
  u'status': 0,
  u'topic_ids': [2007,
   2008,
   2009,
   2010,
   2011,
   2012,
   2013,
   2014,
   2015,
   2016,
   2017,
   2018,
   2019,
   2020,
   2021,
   2022,
   2023,
   2024,
   2025,
   2026,
   2027,
   2028,
   2029,
   2030,
   2031,
   2032],
  u'user_id': 44,
  u'white_list': []}]
In [80]:
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn