[Fixed]-What is the best way to use elasticsearch in Django Restframework

1👍

After pricking my head and researching all over the web i created this solution which is very straight forward.

from elasticsearch import Elasticsearch, RequestsHttpConnection
import datetime
import socket
from requests_aws4auth import AWS4Auth


class EsHelper():
    conn = ""
    index = "index"
    HOSTNAME = socket.gethostname()

def __init__(self):
    self.conn = Elasticsearch(['localhost:9200'])



    exist = self.conn.indices.exists(self.index)
    if not(exist):
        self.conn.indices.create('index', body={
            'settings': {
                'analysis': {
                    'filter': {
                        'autocomplete_filter': {
                            'type': 'edge_ngram',
                            'min_gram': 1,
                            'max_gram': 20
                        }
                    },
                    'analyzer': {
                        'autocomplete': {
                            'type': 'custom',
                            'tokenizer': 'standard',
                            'filter': [
                                'lowercase',
                                'autocomplete_filter'
                            ]
                        }
                    }
                },
                'index': {
                    'number_of_shards': '5',
                    'number_of_replicas': '1'
                }
            }, 
        })

def EsAddIndex(self, index, type, id, body):
    self.conn.index(index=index, doc_type=type, id=id, body=body)

def EsUpdateIndex(self, index, type, id, body):
    self.conn.update(index=index, doc_type=type, id=id, body=body)

def EsSearch(self, index, page, size, searchTerm):
    body = {
        'query': {
            'match': searchTerm
        },
        'sort': {
                'created': {
                    'order': 'desc'
                }
        },
        'filter': {
                'term': {
                    'super_verification': 'verified'
                }
        }
    }
    res = self.conn.search(index=index, body=body)
    output = []
    for doc in res['hits']['hits']:
        output.append(doc['_source'])
    return output

Leave a comment