Read and Write Files From Elasticsearch With R
-
Install the following package:
library(elastic)
-
Connect to Elasticsearch by running the following lines of code:
# ====== Connection to Elasticsearch ====== # # To connect to Elasticsearch. connect(es_host = "ELASTICSEARCH_IP", port =ELASTICSEARCH_PORT, transport_schema = "http")
The default port is 9200
. -
You can now insert and search documents in Elasticsearch by running the following lines of code:
# ====== Inserting Documents ====== # # Bulk insertion of documents from a .json file included in the package. plosdat <- system.file("examples", "plos_data.json", package = "elastic") docs_bulk(plosdat)
# ====== Searching Documents ====== # # To retrieve all documents in the index (no query given). documents = Search(index = "plos", size = 1)$hits$hits # To retrieve documents from the 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