def get_doc(id, q=None): highlight_class = 'data-charity-account-highlight="true"' es = get_db() body = { "query": { "terms": { "_id": [id], } } } if q: body["highlight"] = { "fields": { "attachment.content": { "number_of_fragments": 0, "pre_tags": [f'<em class="bg-yellow b highlight" {highlight_class}>'], "post_tags": ["</em>"], "highlight_query": { "simple_query_string": { "query": q, "fields": ["attachment.content"], "default_operator": "or", } }, } }, "encoder": "html", } search_doc = es.search( index=current_app.config.get("ES_INDEX"), doc_type="_doc", body=body, _source_excludes=["filedata"], ) if search_doc.get("hits", {}).get("hits", []): doc = search_doc.get("hits", {}).get("hits", [])[0] if doc.get("highlight", {}).get("attachment.content"): content = doc["highlight"]["attachment.content"][0] content = Markup(content).unescape() doc["_highlight_count"] = content.count(highlight_class) doc["_source"]["attachment"]["content"] = content return doc