Search code examples
djangoelasticsearchelasticsearch-dsl

Elastic search querying


I'm having some issues with my elastic search querying. I have the following fields, patientid, patientfirstname, patientmidname, and patientlastname. I want to be able to enter in either one of those 4 fields and get matching results returned. So far my query works only if I use a patientid. If i type something like harry (firstname) or middle/last name it doesn't query it. Individual term querying works for each of them.

q = Q({"bool": { "should": [ {"term":{"patientid":text}}, {"wildcard":{"patientlastname":"*"+text+"*"}}, {"wildcard":{"patientfirstname":"*"+text+"*"}}, {"wildcard":{"patientmidname":"*"+text+"*"}} ]}})

r = Search().query(q)[0:10000]

Solution

  • the matching depends on your analyzers, what I would recommend is to just use:

    Search().query('multi_match', query=text, fields=['patientid', 'patientlastname', 'patientfirstname', 'patientmidname'])
    

    which will query across those fields (you can read about different types of multi_match query in [0]).

    You just need to make sure that all the patient name fields are properly analyzed (see [1] for details)

    0 - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html 1 - https://www.elastic.co/guide/en/elasticsearch/reference/6.4/analysis.html#_index_time_analysis