├── requirements.txt ├── .dockerignore ├── docker-compose.yml ├── NPPES_data └── download.sh ├── Dockerfile ├── nppes_fhir_demo ├── load_data.sh ├── templates │ ├── layout.html │ ├── index.html │ └── fhir_index.html ├── load_nppes_bulk.py └── serve_nppes.py ├── .gitignore ├── README.md └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | Flask >= 0.10.1 2 | elasticsearch >= 6.0.0 3 | gunicorn >= 19.5.0 4 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | NPPES_data/npidata_20050523-20150412.csv 2 | NPPES_data/NPPES_Data_Dissemination_April_2015.zip 3 | .git 4 | 5 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | web: 2 | build: . 3 | ports: 4 | - "8888:8080" 5 | volumes: 6 | - .:/code 7 | - ./NPPES_data:/data 8 | links: 9 | - esdb 10 | esdb: 11 | image: elasticsearch 12 | ports: 13 | - "9200:9200" 14 | - "9300:9300" 15 | -------------------------------------------------------------------------------- /NPPES_data/download.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | wget http://www.nucc.org/images/stories/CSV/nucc_taxonomy_150.csv 4 | #dpm - 15Aug2018 - changed to most recent data file 5 | wget http://download.cms.gov/nppes/NPPES_Data_Dissemination_August_2018.zip 6 | #wget http://nppes.viva-it.com/NPPES_Data_Dissemination_May_2015.zip 7 | #load_nppes_bulk can now read directly from the zip file 8 | #unzip NPPES_Data_Dissemination_April_2015.zip 9 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:2.7 2 | RUN apt-get update && apt-get install unzip 3 | ADD . /code/ 4 | WORKDIR /code/ 5 | RUN pip install -r requirements.txt 6 | VOLUME /data 7 | WORKDIR /code/nppes_fhir_demo 8 | EXPOSE 8080 9 | RUN useradd -ms /bin/bash nppes_server 10 | RUN chown -R nppes_server.nppes_server /code 11 | RUN chown -R nppes_server.nppes_server /data 12 | USER nppes_server 13 | CMD ["gunicorn","-b","0.0.0.0:8080", "serve_nppes:app"] 14 | -------------------------------------------------------------------------------- /nppes_fhir_demo/load_data.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ ! -e "/data/npidata_20050523-20150412.csv" ] 4 | then 5 | cd /data 6 | wget http://nppes.viva-it.com/NPPES_Data_Dissemination_April_2015.zip 7 | unzip NPPES_Data_Dissemination_April_2015.zip 8 | rm NPPES_Data_Dissemination_April_2015.zip 9 | fi 10 | 11 | if [ ! -e "/data/nucc_taxonomy_150.csv" ] 12 | then 13 | cd /data 14 | wget http://www.nucc.org/images/stories/CSV/nucc_taxonomy_150.csv 15 | fi 16 | 17 | python /code/nppes_fhir_demo/load_nppes_bulk.py \ 18 | /data/npidata_20050523-20150412.csv \ 19 | /data/nucc_taxonomy_150.csv 20 | -------------------------------------------------------------------------------- /nppes_fhir_demo/templates/layout.html: -------------------------------------------------------------------------------- 1 | Flask AJAX Demo 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | {% block content %}{% endblock %} 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | npidata_*.csv 2 | NPPES_data/* 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *,cover 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | 57 | # Sphinx documentation 58 | docs/_build/ 59 | 60 | # PyBuilder 61 | target/ 62 | -------------------------------------------------------------------------------- /nppes_fhir_demo/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | {% block content %} 3 | 31 | 32 |
33 |
34 | Search for a providerX - enter name and/or city, state, specialty
line twod adf sad fsad ff
35 | 36 |

37 | 38 |

39 |
40 |

41 |

42 | 43 | 44 |
45 |

46 |

Matching Providers 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 |
First NameLast NameTitleCityStateDirectSpecialtySub-specialty
First NameLast NameTitleCityStateDirectSpecialtySub-specialty
74 | {% endblock %} 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nppes_fhir_demo 2 | A simple hack/demonstration of how to search and access a locally-copied CMS provider directory (NPPES) via elasticsearch and early DST FHIR services 3 | 4 | Addendum Aug 2018 - some additional hacks to this otherwise abandoned project: 5 | 6 | - upgraded to python 3 7 | - upgraded to elasticsearch 6.* 8 | - added a few demo tweaks to the search form 9 | 10 | NOTE what's still missing (and won't likely get added) 11 | 12 | - does not support current FHIR resources - sorry, but this was merely to prove that it could be done! 13 | - does not support the new CMS "endpoints" directory information 14 | - does not support the relatively new CMS "additional names" and "secondary address" files 15 | 16 | 17 | ### Requires: 18 | 19 | - Python 3 20 | - Elasticsearch - to serve as database for NPPES records (Lucene) 21 | - Flask - simple python web server 22 | - gunicorn - WSGI gateway to expose the Flask app to the web 23 | 24 | 25 | ## Very brief instructions: 26 | 27 | - Install and launch Elasticsearch. I took all the defaults, which is overkill, but it works. On the mac, 'brew' can install elasticsearch and kibana with no problems. To use the phonetic analyzer, you will also need to install the phonetic plugin, using something like this: 28 | - ```sudo bin/elasticsearch-plugin install analysis-phonetic``` 29 | - Use python to "pip install" Flask, elasticsearch, and gunicorn 30 | - Run the "download.sh" script in NPPES_data to download the NPPES file from CMS, and the "taxonomy" file from NUCC. You might need to edit this file to refer to a more recent CMS distribution of the NPPES database! 31 | - the bulk_load_nppes script can now read directly from the zip file, so there is no need to extract the 5GB CSV file 32 | - Run 'python bulk_load_nppes' 33 | - It should find the right ZIP and CSV files. If not, pass them in on the comand line. 34 | - It should default to point to your local install of ElasticSearch. If not, look in the code to see which environment variables to set to point to your instance of ES. 35 | - Loading the ~4.2M records takes about 5-6 minutes on my i7/SSD. Ignore the error messages about non-Ascii provider entries. That's a bug to be fixed, but obly drops a relatively few provider names. You only need to load the provider records into elasticsearch once, of course. 36 | - Run "python serve_nppes' to test locally (defaults to 127.0.0.1:5000/nppes_fhir) 37 | - Optionally deploy to web by running gunicorn to serve up serve_nppes:app (the WSGI entry point.) 38 | - `gunicorn -b 0.0.0.0:80 -w 4 serve_nppes:app` 39 | 40 | 41 | More details: 42 | 43 | Set up git, Python 3, and elasticsearch (somewhere network accessible), then: 44 | 45 | ``` 46 | make sure elasticsearch is running somewhere accessible - the loader program will configure the necessary index 47 | git clone https://github.com/dmccallie/nppes_fhir_demo/ 48 | cd nppes_fhir_demo 49 | pip install -r requirements.txt 50 | cd NPPES_data 51 | sh ./download.sh 52 | cd ../nppes_fhir_demo 53 | python load_nppes_bulk.py 54 | 55 | # in local env 56 | python serve_nppes.py 57 | 58 | # in prod 59 | gunicorn -b 0.0.0.0:8080 serve_nppes:app 60 | ``` 61 | 62 | ## Dockerized version - NOTE: this is NOT been kept up to date. You will have to change some things. 63 | 64 | ### Requirements 65 | 66 | * Install docker (https://docs.docker.com/installation/) 67 | * Install docker-compose (https://docs.docker.com/compose/install/) 68 | 69 | ### Setup 70 | 71 | * Launch the stack: `docker-compose up` 72 | * Load sample data: `docker-compose run web /code/nppes_fhir_demo/load_data.sh` 73 | * Try it: browse to http://container/nppes_fhir or http://host:8888/nppes_fhir 74 | * View logs `docker-compose logs` 75 | -------------------------------------------------------------------------------- /nppes_fhir_demo/load_nppes_bulk.py: -------------------------------------------------------------------------------- 1 | #dpm - 15Aug2018 - updated to python3 2 | import csv, sys 3 | from datetime import datetime 4 | from elasticsearch import Elasticsearch 5 | from elasticsearch import helpers 6 | import json 7 | import time 8 | import os 9 | import argparse 10 | import zipfile 11 | 12 | parser = argparse.ArgumentParser(description='Bulk load NPPES data') 13 | parser.add_argument('npifile', metavar='N', nargs='?', help='Path to NPI data file', 14 | #defaults to the May zip file - may need to edit this 15 | #dpm 15Aug2018 - changed to a more recent dissemination 16 | default="../NPPES_data/NPPES_Data_Dissemination_August_2018.zip") 17 | parser.add_argument('nuccfile', metavar='N', nargs='?', help='Path to NUCC data file', 18 | default="../NPPES_data/nucc_taxonomy_150.csv") 19 | args = parser.parse_args() 20 | 21 | nppes_file = args.npifile #download this 5GB file from CMS! 22 | nucc_file = args.nuccfile 23 | 24 | #this is the reference data used to specificy provider's specialties 25 | def load_taxonomy(nucc): 26 | nucc_dict = {} 27 | with open(nucc, encoding='latin-1') as nucc_file: 28 | nucc_reader = csv.DictReader(nucc_file) 29 | for row in nucc_reader: 30 | code = row['Code'] 31 | classification = row['Classification'] 32 | specialization = row['Specialization'] 33 | if code and classification: 34 | nucc_dict[code] = classification + " " + specialization 35 | return nucc_dict 36 | 37 | def get_specialty(nucc_dict, code_1, code_2, code_3): 38 | #just concatenate together for now 39 | #print (code_1, code_2, code_3) 40 | out = "" 41 | if (code_1): 42 | out += nucc_dict[code_1] 43 | if (code_2): 44 | out += " / " + nucc_dict[code_2] 45 | if (code_3): 46 | out += " / " + nucc_dict[code_3] 47 | return out 48 | 49 | def extract_provider(row, nucc_dict): 50 | #creates the Lucene "document" to define this provider 51 | #assumes this is a valid provider 52 | provider_document = {} 53 | provider_document['npi'] = row['NPI'] 54 | provider_document['firstname'] = row['Provider First Name'] 55 | provider_document['lastname'] = row['Provider Last Name (Legal Name)'] 56 | provider_document['mail_address_1'] = row['Provider First Line Business Mailing Address'] 57 | provider_document['mail_address_2'] = row['Provider Second Line Business Mailing Address'] 58 | provider_document['city'] = row['Provider Business Mailing Address City Name'] 59 | provider_document['state_abbrev'] = row['Provider Business Mailing Address State Name'] 60 | provider_document['credential'] = row['Provider Credential Text'].replace(".","") 61 | provider_document['spec_1'] = nucc_dict.get(row['Healthcare Provider Taxonomy Code_1'],'') 62 | provider_document['spec_2'] = nucc_dict.get(row['Healthcare Provider Taxonomy Code_2'],'') 63 | provider_document['spec_3'] = nucc_dict.get(row['Healthcare Provider Taxonomy Code_3'],'') 64 | 65 | #pseudo field for searching any part of an address 66 | #by creating this as one field, it's easy to do wildcard searches on any combination of inputs 67 | #but it does waste a few hundred MB. 68 | provider_document['full_address'] = provider_document['mail_address_1'] + " " + \ 69 | provider_document['mail_address_2'] + " " + \ 70 | provider_document['city'] + " " + \ 71 | provider_document['state_abbrev'] 72 | 73 | #experiment with an "all" field to allow for a single query line that doesn't require field-by-field query 74 | provider_document['all'] = provider_document['firstname'] + " " + \ 75 | provider_document['lastname'] + " " + \ 76 | provider_document['full_address'] + " " + \ 77 | provider_document['credential'] + " " + \ 78 | provider_document['spec_1'] + " " + \ 79 | provider_document['spec_2'] + " " + \ 80 | provider_document['spec_3'] 81 | 82 | return provider_document 83 | 84 | def convert_to_json(row, nucc_dict): 85 | #some kind of funky problem with non-ascii strings here 86 | #trap and reject any records that aren't full ASCII. 87 | #fix me! 88 | 89 | provider_doc = extract_provider(row, nucc_dict) 90 | try: 91 | j = json.dumps(provider_doc, ensure_ascii=True) 92 | #print("Successful json for ", j) 93 | except Exception: 94 | print("FAILED convert a provider record to ASCII = ", row['NPI']) 95 | #print("Unexpected error:", sys.exc_info()[0]) 96 | j = None 97 | return j 98 | 99 | #create a python iterator for ES's bulk load function 100 | def iter_nppes_data(nppes_file, nucc_dict, convert_to_json): 101 | count = 0 102 | #extract directly from the zip file 103 | zipFileInstance = zipfile.ZipFile(nppes_file, mode='r', allowZip64=True) 104 | for zipInfo in zipFileInstance.infolist(): 105 | #hack - the name can change, so just use the huge CSV. That's the one 106 | if zipInfo.file_size > 4000000000: 107 | print("found NPI CSV file = ", zipInfo.filename) 108 | content = zipFileInstance.open(zipInfo, 'r') #can't use 'rt' anymore 109 | decoded_content = (line.decode('utf8') for line in content) #funky trick to turn py3 bytes to string 110 | reader = csv.DictReader(decoded_content) 111 | for row in reader: 112 | #print("GOT A ROW = ", row['Provider Last Name (Legal Name)']) 113 | if not row['NPI Deactivation Date'] and row['Entity Type Code'] == '1': 114 | if (row['Provider Last Name (Legal Name)']): 115 | npi = row['NPI'] 116 | body = convert_to_json(row, nucc_dict) 117 | if (body): 118 | #action instructs the bulk loader how to handle this record 119 | action = { 120 | "_index": "nppes", 121 | "_type": "provider", 122 | "_id": npi, 123 | "_source": body 124 | } 125 | count += 1 126 | if count % 5000 == 0: 127 | print("Count: Loaded {} records".format(count)) 128 | yield action 129 | 130 | 131 | #dpm 16Aug2018 - added explict creation of indexes to optimize for space, etc 132 | 133 | def create_index(es_object, index_name): 134 | created = False 135 | # index settings 136 | settings = { 137 | "settings": { 138 | "index" : { 139 | "number_of_shards": 2, #doesn't work??? 140 | "number_of_replicas": 0, 141 | }, 142 | "index" : { 143 | "analysis" : { 144 | "filter" : { 145 | "synonym" : { 146 | "type" : "synonym", 147 | "synonyms" : [ #some examples, should be in separate file, etc 148 | "internist => internal", 149 | "gi => gastroenterology", 150 | "knife => surgical, surgeon, surgery", 151 | "obgyn => obstetrics, gynecology", 152 | "peds => pediatric, pediatrics" 153 | ] 154 | }, 155 | "test_phonetic": { 156 | "type": "phonetic", 157 | "encoder": "double_metaphone", 158 | "replace": False 159 | } 160 | }, 161 | "analyzer" : { 162 | "synonym" : { 163 | "tokenizer" : "standard", 164 | "filter" : [ 165 | "lowercase", "synonym" 166 | ] 167 | }, 168 | "phonetic": { 169 | "tokenizer": "standard", 170 | "filter": [ 171 | "standard", "lowercase", "test_phonetic" 172 | ] 173 | } 174 | }, 175 | }, 176 | }, 177 | }, 178 | "mappings": { 179 | "provider": { 180 | "dynamic": "strict", 181 | "properties": { 182 | "npi": { "type": "text"}, 183 | "firstname": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "phonetic" }, 184 | "lastname": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "phonetic" }, 185 | "mail_address_1": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "phonetic" }, 186 | "mail_address_2": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "phonetic" }, 187 | "city": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "phonetic" }, 188 | "state_abbrev": { "type": "text", "norms": False, "index_options": "freqs" }, 189 | "credential": { "type": "text", "norms": False, "index_options": "freqs" }, 190 | "spec_1": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "synonym" }, 191 | "spec_2": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "synonym" }, 192 | "spec_3": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "synonym" }, 193 | 194 | #pseudo-fields 195 | "full_address": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "phonetic" }, 196 | "all": { "type": "text", "norms": False, "index_options": "freqs", "analyzer" : "synonym" }, 197 | }, 198 | }, 199 | #"_doc": { 200 | # "_source": { 201 | # "excludes": [ 202 | # "*.all", #dpm - this doesn't appear to work, don't know why. 203 | # ] 204 | # } 205 | #} 206 | } 207 | } 208 | try: 209 | if es_object.indices.exists(index_name): 210 | es_object.indices.delete(index=index_name, ignore=400) 211 | print("Deleted old index") 212 | 213 | # Ignore 400 means to ignore "Index Already Exist" error. 214 | es_object.indices.create(index=index_name, body=settings) 215 | print('Created new index at {}'.format(index_name)) 216 | created = True 217 | except Exception as ex: 218 | print("index creation exception: ", str(ex)) 219 | finally: 220 | return created 221 | 222 | 223 | #main code starts here 224 | 225 | if __name__ == '__main__': 226 | count = 0 227 | nucc_dict = load_taxonomy(nucc_file) 228 | es_server = os.environ.get('ESDB_PORT_9200_TCP_ADDR') or '127.0.0.1' 229 | es_port = os.environ.get('ESDB_PORT_9200_TCP_PORT') or '9200' 230 | 231 | es = Elasticsearch([ 232 | '%s:%s'%(es_server, es_port) #point this to your elasticsearch service endpoint 233 | ]) 234 | 235 | start = time.time() 236 | print ("start at", start) 237 | 238 | create_index(es, index_name='nppes') 239 | 240 | #invoke ES bulk loader using the iterator 241 | helpers.bulk(es, iter_nppes_data(nppes_file,nucc_dict,convert_to_json)) 242 | 243 | print ("total time - seconds", time.time()-start) 244 | -------------------------------------------------------------------------------- /nppes_fhir_demo/serve_nppes.py: -------------------------------------------------------------------------------- 1 | #dpm 15Aug2018 - ported to python3 2 | 3 | from flask import Flask, jsonify, render_template, request, Response 4 | import elasticsearch 5 | import json 6 | import urllib, urllib.parse 7 | from collections import OrderedDict #use ordered dictionary to preserve JSON order 8 | from uuid import uuid4 9 | 10 | #creates WSGI entry point for gunicorn 11 | app = Flask(__name__) 12 | es = "" 13 | 14 | 15 | #starting point for FHIR Practivtioner demo - yields the search form 16 | @app.route('/nppes_fhir') 17 | def nppes_fhir(): 18 | return render_template('fhir_index.html') 19 | 20 | 21 | #FHIR Practitioner by /npi 22 | @app.route('/nppes/Practitioner/', methods=['GET']) 23 | def handle_npi_lookup(npi): 24 | #query was for a specific provider 25 | #return the FHIR Practitioner record 26 | #npi = request.args.get('_id', '').strip() 27 | query = "npi:" + npi 28 | try: 29 | es_reply = es.search(index='nppes', doc_type="provider", q=query) 30 | except: 31 | print("FAILED to query ES ") 32 | raise 33 | if (es_reply and (es_reply['hits']['total'] == 1)): 34 | 35 | hits = es_reply['hits']['hits'] 36 | 37 | prac = build_fhir_Practitioner(hits[0]['_source']) 38 | return Response(json.dumps(prac, indent=2, separators=(',', ': ')), mimetype="application/json") 39 | 40 | else: 41 | return jsonify("") 42 | 43 | 44 | 45 | #FHIR Practitioner search service - returns FHIR Bundle of matching Pracitioner matches 46 | @app.route('/nppes/Practitioner', methods=['GET']) 47 | def fhir_lookup(): 48 | 49 | #only supports these FHIR fields for demo 50 | anystring = request.args.get('anystring', '').strip() #dpm - added for demo of open-ended query approach 51 | npi = request.args.get('_id', '').strip() 52 | family = request.args.get('family', '').strip() 53 | given = request.args.get('given', '').strip() 54 | address = request.args.get('address', '').strip() 55 | qualification = request.args.get('qualification', '').strip() 56 | #specialty_code = request.args.get('specialty').strip() #for now, this gets IGNORED! 57 | specialty_text = request.args.get('specialty:text', '').strip() #FHIR uses :text for text search on tokens 58 | page = request.args.get('page', 1, type=int) #which page to start with 59 | count = request.args.get('_count', 15, type=int) #results per page 60 | 61 | #calculate starting point 62 | startfrom = (page-1) * count 63 | 64 | queryText = "" 65 | wildcard = "*" #lucene wildcard is applied to some of the search parameters 66 | fuzzy = "~" 67 | 68 | #if 'anystring' is not empty, do the whole query with terms contained in the string 69 | #this means no special weighting of lastname, etc 70 | #it's an experiment 71 | 72 | if len(anystring)>0: 73 | #strip periods and dashes 74 | anystring = anystring.replace(".","").replace("-","") 75 | #split into words to form query terms 76 | #test support of wildcard AND fuzzy match, using an "OR" approach 77 | #e.g., to query for "mcca~*" will try (mcca~ OR mcca*) -- maybe less explosion? 78 | #note that you can do "term~*" but the term explosion is huge 79 | 80 | queryText = "all:( " #force query against the "all" field 81 | for term in anystring.split(): 82 | #synonyms don't work if wildcard or fuzzy is added to term. weird. 83 | queryText += "( {t} OR {t}{f} OR {t}{w} )".format(t=term, f=fuzzy, w=wildcard) 84 | queryText += " )" 85 | 86 | else: 87 | 88 | #build a Lucene query string - see Lucene documentation for syntax 89 | #dpm - for phonectic experiments, drop the wildcard for the phonetic, but OR it in for non-phonetic 90 | # probably ought to have separate fields for the phonetic vs non-phonetic?? 91 | 92 | wildcard = "*" 93 | if family: 94 | queryText += "lastname:( {f} OR {f}{w} )^4 ".format(f=family, w=wildcard) 95 | if given: 96 | queryText += "firstname:( {g} OR {g}{w} ) ".format(g=given,w=wildcard) 97 | if address: 98 | #apply wildcard to each part of whatever user entered (street, city, state code) 99 | for term in address.split(): 100 | #this is a hack - probably need these fields to be individually named 101 | # hack2 = if field is len==2, assume it's a state code (fixme doh!) 102 | if len(term) == 2: 103 | queryText += "full_address:({t}) ".format(t=term) 104 | else: 105 | queryText += "full_address:( {t} OR {t}{w} ) ".format(t=term, w=wildcard) 106 | 107 | if qualification: queryText += "credential:" + qualification + " " 108 | if specialty_text: 109 | specText = "" 110 | #allow for either spec_1 OR spec_2 to qualify. Everything else is an AND 111 | for term in specialty_text.split(): 112 | #in order for synonyms to work, you need the term without the wildcard??? 113 | wildcard = "*" 114 | specText += " spec_1:({t} OR {t}{w}) OR spec_2:({t} OR {t}{w}) ".format(t=term, w=wildcard) 115 | 116 | queryText += " (" + specText + ") " 117 | 118 | print ("generated Lucene query = ", queryText) #debug 119 | 120 | #invoke ElasticSearch using the "lucene query mode" 121 | try: 122 | es_reply = es.search(index='nppes', default_operator="AND", size=count, from_=startfrom, q=queryText) 123 | except: 124 | print ("FAILED to query ES ") 125 | raise 126 | #print "es reply = ", es_reply 127 | 128 | data = "" 129 | total = es_reply['hits']['total'] #total matches 130 | time = es_reply['took'] #milliseconds of ES time 131 | 132 | #get root of results 133 | #print("es reply = ", es_reply) 134 | 135 | hits = es_reply['hits']['hits'] 136 | providers = [] 137 | if (len(hits) > 0): 138 | done = False 139 | for h in hits: 140 | src = h['_source'] 141 | a_doc = build_fhir_Practitioner(src) 142 | providers.append(a_doc) 143 | else: 144 | done = True 145 | 146 | #calculate URLs for next and prev page. 147 | request_params = request.args.copy() 148 | 149 | if ((not done) and len(providers) >= count): 150 | request_params['page'] = page + 1 151 | nextUrl = request.base_url + "?" + urllib.parse.urlencode(request_params) 152 | else: 153 | nextUrl = '' 154 | 155 | if page > 1: 156 | request_params['page'] = page - 1 157 | prevUrl = request.base_url + "?" + urllib.parse.urlencode(request_params) 158 | else: 159 | prevUrl = '' 160 | 161 | 162 | the_bundle = build_fhir_bundle(total, time, providers, nextUrl, prevUrl, startfrom) 163 | 164 | #use Flask Response class instead of jsonify() in order to control JSON use of OrderedDict 165 | return Response(json.dumps(the_bundle, indent=2, separators=(',', ': ')), mimetype="application/json") 166 | 167 | #utility routines 168 | def build_fhir_Practitioner(es_provider_doc): 169 | #convert the results of an ES match to FHIR Practitioner record format 170 | #build with python structures and then JSONify 171 | #this is a total hack approach. proof of concept with lots of gaps! 172 | # NOTE: this is a very old version of FHIR's Practitioner! Needs to be re-mapped to newer STU 173 | 174 | prac = OrderedDict() #allows preservation of dictionary names, for easier debugging 175 | #note that OrderedDict literal inits are ugly, e.g.: OrderedDict( [ (tuple), (tuple) ] ) 176 | 177 | prac['resourceType'] = "Practitioner" 178 | prac['id'] = es_provider_doc.get('npi',"0") 179 | prac['identifier'] = [OrderedDict([ 180 | ('use', "official"), 181 | ('system', "http://hl7.org/fhir/sid/us-NPI????"), 182 | ('value', es_provider_doc.get('npi',"0")), 183 | ])] 184 | prac['name'] = OrderedDict([ 185 | ("use", "official"), 186 | ("family", [ es_provider_doc.get('lastname')]), 187 | ("given", [ es_provider_doc.get('firstname')]), 188 | ("suffix", [ es_provider_doc.get('credential')]) 189 | ]) 190 | prac['gender'] = "unknown" 191 | address_line = es_provider_doc.get('mail_address_1') 192 | if es_provider_doc.get('mail_address_2'): 193 | address_line += "
" + es_provider_doc.get('mail_address_2') 194 | prac['address'] = OrderedDict([ 195 | ("use", "work"), 196 | ("line", [ address_line ]), 197 | ("city", es_provider_doc.get('city')), 198 | ("state", es_provider_doc.get('state_abbrev')), 199 | ("country", "USA") 200 | ]) 201 | prac['telecom'] = [ OrderedDict([ 202 | ("extension", [ 203 | { 204 | "url" : "http://hl7.org/fhir/StructureDefinition/us-core-direct", 205 | "valueBoolean" : True 206 | } 207 | ]), 208 | ("system", "email"), 209 | ("value", es_provider_doc.get('firstname')[0:1] + "." + es_provider_doc.get('lastname') + "@direct.somehist.com"), 210 | ("use", "work") 211 | ])] 212 | 213 | if es_provider_doc.get('spec_1'): 214 | prac['practitionerRole'] = [{ 215 | "specialty": [ 216 | { 217 | "coding": [{ 218 | "system": "http://www.wpc-edi.com/codes/taxonomy", 219 | "code": "??" 220 | }], 221 | "text": es_provider_doc.get('spec_1') 222 | }] 223 | }] 224 | if es_provider_doc.get('spec_2'): 225 | prac['practitionerRole'][0]['specialty'].append( 226 | { 227 | "coding": [{ 228 | "system": "http://www.wpc-edi.com/codes/taxonomy", 229 | "code": "??" 230 | }], 231 | "text": es_provider_doc.get('spec_2') 232 | } 233 | ) 234 | 235 | return prac 236 | 237 | def build_fhir_bundle(total, time, providers, nextUrl, prevUrl, startfrom): 238 | #wrap the results into a FHIR bundle. Ugh. 239 | 240 | bundle = OrderedDict() 241 | 242 | #first, some header stuff. 243 | bundle["resourceType"] = "Bundle" 244 | bundle["id"] = str(uuid4()) #not sure why we need this, but GG says so 245 | bundle["type"] = "searchset" 246 | bundle["base"] = "http://davidmccallie.com/nppes" 247 | bundle["total"] = total 248 | 249 | #set up the pageing links 250 | bundle["link"] = [ 251 | { 252 | "relation": "next", 253 | "url": nextUrl 254 | }, 255 | { 256 | "relation" : "prev", 257 | "url" : prevUrl 258 | } 259 | ] 260 | 261 | #then, convert each matching practitioner into a entry.resource 262 | bundle["entry"] = [] 263 | for prov in providers: 264 | bundle["entry"].append({ "resource" : prov}) 265 | 266 | return bundle 267 | 268 | 269 | #main program here 270 | 271 | import os 272 | es_server = os.environ.get('ESDB_PORT_9200_TCP_ADDR') or '127.0.0.1' 273 | es_port = os.environ.get('ESDB_PORT_9200_TCP_PORT') or '9200' 274 | 275 | try: 276 | es = elasticsearch.Elasticsearch([ 277 | '%s:%s'%(es_server, es_port) #point this to your elasticsearch service endpoint 278 | ]) 279 | print ("connected to ES") 280 | except: 281 | print ("FAILED to connect to ES ") 282 | raise 283 | 284 | #if called locally (without gunicorn) then run on localhost port 5000 for debugging 285 | #otherwise, gunicorn will invoke the "app" entrypoint for WSGI conversation 286 | if __name__ == '__main__': 287 | app.run(host="127.0.0.1", port=5000, debug=True) 288 | -------------------------------------------------------------------------------- /nppes_fhir_demo/templates/fhir_index.html: -------------------------------------------------------------------------------- 1 | 2 | {% extends "layout.html" %} 3 | {% block content %} 4 | 5 | 6 | 197 | 198 | 199 | 202 | 203 |
204 |
205 | Search for a provider - enter name and/or address (street, city, state,) credential, or specialty
206 | NOTE: 'Any String' field uses fuzzy match and wildards
207 | BUT the named fields use wildcard and phonetic (double metaphone) 208 |
209 | 210 |

211 | 212 |
213 | 214 |
215 | 216 |
217 | 218 |
219 | 220 |
221 |
222 | 223 | 224 | 225 | 226 |
227 |
228 | 229 | 230 |
231 | 232 | 233 | 234 | 235 |
236 | 237 | 238 | 240 |
241 | 242 |
Matching Providers
243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 |
 NPI First NameLast NameCredentialAddressDirectSpecialtySub-specialty
 NPI First NameLast NameCredentialAddressDirectSpecialtySub-specialty
278 | 279 | {% endblock %} 280 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------