Source

pyDatalog / pyDatalog / examples / Mongo.py

"""
This file shows how to use pyDatalog to query 
a relational database and a noSQL database simultaneously.

It has 3 parts :
    1.initialize the Mongo database
    2. define a predicate resolver for Employee.diploma 
    3. query data from both Mongo DB and SQLite
"""

""" 1.initialize the Mongo database  """

from pymongo import Connection
connection = Connection()
db = connection.Employees
profiles = db.profiles

profiles_to_insert = [{"name": "John", "diploma": "MSc."},
                     {"name": "Mary", "diploma": "EE"},
                     {"name": "Sam", "diploma": "MBA"}]

profiles.insert(profiles_to_insert)

""" 2. define a predicate resolver for Employee.diploma """

from SQLAlchemy import Employee # import the SQLAlchemy example

def _pyD_diploma2(cls, employee, diploma):
    global profiles
    if employee.is_const():
        r = profiles.find_one({"name": employee.id.name})
        if r: yield (employee, r["diploma"])
        return
    raise AttributeError

Employee._pyD_diploma2 = classmethod(_pyD_diploma2) # attach the resolver to the Employee class

""" 3. query data from both Mongo DB and SQLite """

from pyDatalog import pyDatalog

print("\n *** combined SQLite and Mongo query :\n")
X, N, Diploma = pyDatalog.variables(3)

# Who has a salary of 6800 and a MSc. diploma
(Employee.salary[X]==6800) & (Employee.diploma[X]=="MSc.")
print(X)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.