salmanwahed
salmanwahed

Reputation: 9647

How to do mapping while indexing in elasticsearch

I am using ElasticSearch in a website where i index data from MongoDB.

def postToEs(self):
    """
    put data to the elasticsearch
    """
    es = Elasticsearch()
    cursor = self.getMongoData()
    for document in cursor:
        esdoc={}
        esdoc["category"] = document.get("category")
        esdoc["description"] = document.get("description")
        esdoc["title"] = document.get("title")
        esdoc["link"] = document.get("link")
        esdoc["state"] = document.get("state")
        esdoc_id = esdoc["link"]
        es.index(
            index = 'news',
            doc_type = 'allnews',
            id = esdoc_id,
            body = json.dumps(esdoc)
        )

This worked good. But currently I have to search in the state field for an exact match in elasticsearch. Currently if I search for entries for New York it also gives result of New Hampshire. I have found This link and saw elasticsearch documentation that I need to add mapping on the data. My question is how do I add a mapping on the data in the current scenario? or is there any better way of doing it?

Upvotes: 2

Views: 7067

Answers (1)

BlackPOP
BlackPOP

Reputation: 5737

Delete the existing index

curl -XDELETE "http://hostname:9200/index/type"

Delete the existing river config index

curl -XDELETE "http://hostname:9200/_river"

Create mapping to index

curl -XPUT "http://hostname:9200/index/type/_mapping" -d'
{
"allnews": {
    "properties": {
        "category": {
            "type": "string"
        },
        "description": {
            "type": "string"
        },
        "link": {
            "type": "string"
        },
        "state": {
            "type": "string",
            "index" : "not_analyzed"
        },
        "title": {
            "type": "string"
        }
    }
}
}'

After these steps put the river plugin config sync mongodb to elasticsearch.

HOpe it helps..!

Upvotes: 6

Related Questions