jeewonb
jeewonb

Reputation: 75

Elasticsearch - match API with paramter field

My code is like this:

const [fieldName, setFieldName] = useState('');

    ...

const selectFieldItem = name => {
    setFieldName(name);
    console.log('selected field: ', fieldName);
  };
    ...

const getDocuments = async () => {
        try {
          if (selectedIndexName || value) {
            const response = await client.search({
              index: value,
              body: {
               query: {
                 match: {
                    fieldName: element,
                 },
               },
              },
            });
            console.log('documents', response.hits.hits);
            setDocuments(response.hits.hits);
          }
        } catch (error) {
          console.trace(error.message);
        }
      };

The thing is that fieldName is a parameter. So it should be like

"match": 
   {
      "TXN_CODE": "1"
   }

But elasticsearch understands it as a string 'fieldName' like below

"match": 
   {
      "fieldName": "1"
   }

Any advice for this?

I also tried this, but didn't work.

const response = await client.search({
          index: value,
          body: {
            query: {
              match: {
                '{{fieldName}}': element,
              },
            },
          },
          params: {
            fieldName: fieldName,
          },
        });

Upvotes: 0

Views: 38

Answers (1)

Alkis Kalogeris
Alkis Kalogeris

Reputation: 17765

const response = await client.search({
  index: value,
  body: {
   query: {
     match: {
        [fieldName]: element,
     },
   },
  },
});

You can learn more about this by searching about variable as json key

Upvotes: 1

Related Questions