R - Index & Search documents from ElasticSearch


Common part

Libraries dependency

library(elastic)

ElasticSearch Connection

Default port is 9200

Connection

# ====== Connection ====== #
# Connection to ElasticSearch
connect(es_host = "ELASTICSEARCH_IP:ELASTICSEARCH_PORT")

How to insert a document in ElasticSearch with Python ?

Code example

# ====== Inserting Documents ====== #
# Bulk inserting documents. From a json file included in the package.
plosdat <- system.file("examples", "plos_data.json", package = "elastic")
docs_bulk(plosdat)

How to search a document in ElasticSearch with Python ?

Code example

# ====== Searching Documents ====== #
# Retrieving all documents in index (no query given)
documents = Search(index = "plos", size = 1)$hits$hits

# Retrieving documents in index that match a query
body <- '{
 "query": {
   "more_like_this": {
     "fields": ["abstract","title"],
     "like_text": "and then",
     "min_term_freq": 1,
     "max_query_terms": 12
   }
 }
}'
Search('plos', body=body)$hits$total