Simple Python3 CLI for searching using Postgres and SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from sqlalchemy import create_engine, Column, Integer, String | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.dialects.postgresql import TSVECTOR | |
from sqlalchemy.orm import sessionmaker | |
# Create DB Session | |
engine = create_engine('postgresql://iain:password@localhost:5432/Real-World') | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
Base = declarative_base() | |
class OpenNames(Base): | |
__tablename__ = 'open_names' | |
# Map DB columns we're interested in | |
ogc_fid = Column(Integer, primary_key=True) | |
text = Column(String) | |
textsearchable = Column(TSVECTOR) | |
def search_address(self, search_for: str): | |
print(search_for) | |
or_search = search_for.replace(' ', ' | ') # Append OR operator to every word searched | |
results = session.query(OpenNames.text).filter(OpenNames.textsearchable.match(or_search, postgresql_reconfig='english')) | |
for result in results: | |
print(result.text) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('address', help='Address you want to search for') | |
args = parser.parse_args() | |
open_names = OpenNames() | |
open_names.search_address(args.address) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment