# Retrieve data directly from Elasticsearch index in React App

**URL:** <https://discuss.elastic.co/t/retrieve-data-directly-from-elasticsearch-index-in-react-app/334365>\
**Category:** Elasticsearch\
**Created:** [May 25, 2023, 7:25pm UTC](https://discuss.elastic.co/t/retrieve-data-directly-from-elasticsearch-index-in-react-app/334365 "2023-05-25T19:25:29Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Thomas\_Makrigiannis](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/thomas_makrigiannis/32/121434_2.png) [@Thomas\_Makrigiannis](https://discuss.elastic.co/u/Thomas_Makrigiannis)\
**Post date:** [May 25, 2023, 7:25pm UTC](https://discuss.elastic.co/t/retrieve-data-directly-from-elasticsearch-index-in-react-app/334365/1 "2023-05-25T19:25:30Z")

</div>

Hi, everyone. I am new to elasticsearch and I really need your help.  
i have construced a react app that simulates a search engine. My app uses node.js and express. I have built both a server and a client. In the app I retrieve data directly from an index, I create a documentObject and then I ahve a query in order that the user gets the desired results. The app and the whole implementation in my local pc works like a charm. But when I deploy my app in a VM online and do all the respective changes concerning the server IP and the app always return as results an empty array. No errors occur in network or response neteir in the server or th client.  
The code that I use to retrieve the data, and works perfect in local implementation, is :

```auto
const express = require("express");
const router = express.Router();
const axios = require("axios");
const client = require("../elasticsearch/client");
require("log-timestamp");

router.get("/documents", async function (req, res) {
  console.log("Loading Application...");
  res.json("Running Application...");

  const indexData = async () => {
    try {
      console.log("Retrieving data from the Elastic Search Index");

      const data = await client.search({
        index: "diavgeia_data_and_entities_index_2",
        // index: "diavgeia_fields_and_entities_out3",
        size: 10000, 
      });

      console.log(data);
      const results = data.hits.hits.map((hit) => hit._source);

      console.log("Data retrieved!");

      console.log("Indexing data...");

      await Promise.all(
        results.map(async (result) => {
          const documentObject = {
            ada: result.ada,
            AFM: result.AFM,
            AMKA: result.AMKA,
            CARDINAL: result.CARDINAL,
            DATE: result.DATE,
            DECISION: result.DECISION,
            decisionTypeLabel: result.decisionTypeLabel,
            decisionTypeUid: result.decisionTypeUid,
            documentUrl: result.documentUrl,
            DOMAIN: result.DOMAIN,
            EMAIL: result.EMAIL,
            EVENT: result.EVENT,
            FAC: result.FAC,
            GPE: result.GPE,
            HASHTAG: result.HASHTAG,
            IBAN: result.IBAN,
            issueDate: result.issueDate,
            LANGUAGE: result.LANGUAGE,
            LAW: result.LAW,
            LOC: result.LOC,
            MENTION: result.MENTION,
            MONEY: result.MONEY,
            NORP: result.NORP,
            ORIGINAL: result.ORIGINAL,
            ORG: result.ORG,
            organizationLabel: result.organizationLabel,
            organizationUid: result.organizationUid,
            PERCENT: result.PERCENT,
            PERSON: result.PERSON,
            PHONE: result.PHONE,
            PRODUCT: result.PRODUCT,
            protocolNumber: result.protocolNumber,
            QUANTITY: result.QUANTITY,
            subject: result.subject,
            submissionTimestamp: result.submissionTimestamp,
            TIME: result.TIME,
            URL: result.URL,
            WORK_OF_ART: result.WORK_OF_ART,
          };

          await client.index({
            index: "diavgeia_data_and_entities_index_2",
            // index: "diavgeia_fields_and_entities_out3",
            id: result.id,
            body: documentObject,
            // pipeline: "diavgeia_data_and_entities_index-pipeline",
          });
        })
      );

      console.log("Data has been indexed successfully!");
    } catch (err) {
      console.log(err);
    }
    console.log("Preparing for the next round of indexing...");
  };
  indexData();
});
module.exports = router;

```

The commented out index is the one of the server. Also the query that I am running in the server is:

```auto
const { Client } = require("@elastic/elasticsearch");
const express = require("express");
const client = require("./elasticsearch/client");
const cors = require("cors");

const app = express();

const data = require("./data_management/retrieve_and_ingest_data_diavgeia");

app.use("/ingest_data", data);

app.use(cors());

app.get("/results", (req, res) => {
  const criteria = [
    {
      range: {
        "@timestamp": {
          gte: `now-${req.query.dateRange}d/d`,
          lt: "now/d",
        },
      },
    },
  ];

  if (req.query.ada) {
    criteria.push({
      match_phrase: { ada: req.query.ada },
    });
  }

  if (req.query.AFM) {
    criteria.push({
      match_phrase: { AFM: req.query.AFM },
    });
  }

  if (req.query.AMKA) {
    criteria.push({
      match_phrase: { AMKA: req.query.AMKA },
    });
  }

  if (req.query.decisionTypeUid) {
    criteria.push({
      match_phrase: { decisionTypeUid: req.query.decisionTypeUid },
    });
  }

  if (req.query.EMAIL) {
    const email = req.query.EMAIL;
    criteria.push({
      wildcard: { EMAIL: `*${email}*` },
    });
  }

  if (req.query.LAW) {
    criteria.push({
      match_phrase: { LAW: req.query.LAW },
    });
  }

  if (req.query.PERSON) {
    criteria.push({
      match_phrase: { PERSON: req.query.PERSON },
    });
  }

  if (req.query.PHONE) {
    criteria.push({
      match_phrase: { PHONE: req.query.PHONE },
    });
  }

  if (req.query.protocolNumber) {
    const protocolNumberv = req.query.protocolNumber;
    criteria.push({
      wildcard: { protocolNumber: `*${protocolNumberv}*` },
    });
  }

  async function sendESRequest() {
    try {
      const body = await client.search({
        index: "diavgeia_data_and_entities_index_2",
        // index: "diavgeia_fields_and_entities_out3",
        body: {
          size: 10000,
          query: {
            bool: {
              must: criteria,
            },
          },
        },
      });
      res.json(body.hits.hits);
    } catch (error) {
      console.error("Elasticsearch search error:", error);
      res.status(500).json({ error: "Internal server error" });
    }
  }
  sendESRequest();
});

const PORT = process.env.PORT || 3001;

app.listen(PORT, () => console.group(`Server started on ${PORT}`));

```

All respective changes on the VM server are made. Any ideas why is this possibly happening? Thank you in advance.

---

<div class="post-metadata">

**Author:** ![carly.richmond](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/carly.richmond/32/104935_2.png) [@carly.richmond](https://discuss.elastic.co/u/carly.richmond)\
**Post date:** [May 26, 2023, 3:54pm UTC](https://discuss.elastic.co/t/retrieve-data-directly-from-elasticsearch-index-in-react-app/334365/2 "2023-05-26T15:54:41Z")

</div>

Hi @Thomas_Makrigiannis,

I can think of a couple of things to check. Are you getting any results running the same query manually via curl rather than in the app? Is there any errors in the Elasticsearch log. And is there data in the index you are querying against in your deployed app (since you have commented out the index I'm assuming they are different compared to local development).

Where is your Elastic cluster deployed to? If it's cloud it might be worth having a look at the [CORS settings as per the documentation](https://www.elastic.co/guide/en/elasticsearch/reference/8.8/modules-network.html).

---

<div class="post-metadata">

**Author:** ![Thomas\_Makrigiannis](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/thomas_makrigiannis/32/121434_2.png) [@Thomas\_Makrigiannis](https://discuss.elastic.co/u/Thomas_Makrigiannis)\
**Post date:** [May 26, 2023, 4:31pm UTC](https://discuss.elastic.co/t/retrieve-data-directly-from-elasticsearch-index-in-react-app/334365/3 "2023-05-26T16:31:30Z")

</div>

Hi @carly.richmond ,  
thank you for reaching out.  
In my server the index is the `diavgeia_fields_and_entities_out3` and above is commented out because it was the code as running in my local machine, but in the server it is changed. In my server when I do:`curl -X GET http://localhost:9200/diavgeia_fields_and_entities_out3/_search` I have all the results returned. Although when I do `curl -v GET 'http://localhost:3001/results?decisionTypeUid=&ada=&AFM=&AMKA=&EMAIL=&LAW=&PERSON=&PHONE=&protocolNumber=&dateRange=365'` I have an empty array returned.  
The Elastic cluster is not deployed in cloud.  
As for handling the CORS settings I have in my server.js :  
`const cors = require("cors"); ... app.use(cors());`  
Finally, the logs look fine ... 🫤 🤷‍♂️  
Should I elaborate more with CORS?  
Any other idea?  
Thank you in advance.

---

<div class="post-metadata">

**Author:** ![carly.richmond](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/carly.richmond/32/104935_2.png) [@carly.richmond](https://discuss.elastic.co/u/carly.richmond)\
**Post date:** [May 30, 2023, 10:19am UTC](https://discuss.elastic.co/t/retrieve-data-directly-from-elasticsearch-index-in-react-app/334365/4 "2023-05-30T10:19:09Z")

</div>

> [@Thomas\_Makrigiannis](#):
>
> curl -v GET '[http://localhost:3001/results?decisionTypeUid=&ada=&AFM=&AMKA=&EMAIL=&LAW=&PERSON=&PHONE=&protocolNumber=&dateRange=365](http://localhost:3001/results?decisionTypeUid=&ada=&AFM=&AMKA=&EMAIL=&LAW=&PERSON=&PHONE=&protocolNumber=&dateRange=365)

Have you run the query with the same criteria directly against Elasticsearch to see if there is results matching that query? Your call to the `_search` API will return all results as you don't have any match criteria specified.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [June 27, 2023, 10:19am UTC](https://discuss.elastic.co/t/retrieve-data-directly-from-elasticsearch-index-in-react-app/334365/5 "2023-06-27T10:19:20Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
