Created
October 16, 2015 14:44
-
-
Save sangheestyle/7d9798518611a8eb8625 to your computer and use it in GitHub Desktop.
Simple experiement on using suggestor in ES
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from datetime import datetime | |
| from elasticsearch import Elasticsearch | |
| es = Elasticsearch() | |
| es.indices.create("brands") | |
| # Mapping for suggester | |
| # It should include [property]_suggest property for suggester | |
| mapping = { | |
| "brand": { | |
| "properties": { | |
| "name": {"type": "string"}, | |
| "name_suggest": {"type": "completion", "payloads": "false"} | |
| } | |
| } | |
| } | |
| es.indices.put_mapping(index="brands", doc_type="brand", body=mapping) | |
| # Indexing documents | |
| brands = [ | |
| {'name': 'advil', 'name_suggest': 'advil'}, | |
| {'name': 'tylenol', 'name_suggest': 'tylenol'}, | |
| {'name': 'motrin', 'name_suggest': 'motrin'} | |
| ] | |
| for idx, brand in enumerate(brands): | |
| res = es.index(index="brands", doc_type='brand', id=idx, body=brand) | |
| print(res['created']) | |
| es.indices.refresh(index="brands") | |
| # Searching documents | |
| res = es.search(index="brands", body={"query": {"match_all": {}}}) | |
| print("Got %d Hits:" % res['hits']['total']) | |
| for hit in res['hits']['hits']: | |
| print("%(name)s" % hit["_source"]) | |
| # Use suggesters: https://goo.gl/uuWMwA | |
| sugg_doc = { | |
| 'suggestions' : { | |
| 'text' : 'a', | |
| 'completion' : { | |
| 'field' : 'name_suggest' | |
| } | |
| } | |
| } | |
| res = es.suggest(body=sugg_doc, index="brands", params=None) | |
| print(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment