Filter by multiple fields in one document (one field more than other field)

Hi!
I am pretty new to elasticsearch. Is there is a way to filter my search results by comparing two values in one document?

I have two fields in my document: inStock, inOtherStock and 3 filter values like: show me all, show me only negative, only positive.

So if
'show me all', I should get all data without filter
'show me only negative' i should get only documents where inStock < inOtherStock
'only positive' I should get only docs where inStock > inOtherStock

My search looks like this:

(search, filterValue)

return {
      body: {
        query: {
          query_string: {
            query: search`,
            fields: [
              'name',
              'sku',
              'bundleId',
              'orders.poNumber',
              'otherIndex.ownerEmail',
              'otherIndex.modifiedProductName',
              'inStock',
              'inOtherStock',
            ],
            analyzer: 'standard',
          },
        },
        sort: [{ _id: { order: 'desc' } }],
      },
    };

I have done this in next way. Is there are a way to make it better?

export const getFilterScript = (quantityDiff) => {
  switch (quantityDiff) {
    case PRODUCTS_QUANTITY_FILTER.SHORTAGE: {
      return {
        script: {
          script: "doc['inStock'].value > doc['inOtherStock'].value"
        }
      }
    }

    case PRODUCTS_QUANTITY_FILTER.OVERRAGE: {
      return {
        script: {
          script: "doc['inStock'].value < doc['inOtherStock'].value"
        }
      }
    }

    default: {
      return {
        script: {
          script: "return true"
        }
      }
    }
  }
}
// quantityDiff = 'show me all' | 'show me only negative' | 'only positive' 

const filter = getFilterScript(quantityDiff); 

return {
      body: {
        query: {
          bool: {
            must: [
              {
                ...filter,
              },
              {
                query_string: {
                  query: search,
                  fields: [
                   'name',
                   'sku',
                   'bundleId',
                   'orders.poNumber',
                   'otherIndex.ownerEmail',
                   'otherIndex.modifiedProductName',
                   'inStock',
                   'inOtherStock',
                  ],
                  analyzer: 'standard',
                },
              }
            ]
          },
        },
        sort: [{ _id: { order: 'desc' } }],
      },
    };

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