title: Mixing user data with ElasticSearch
body: <p>I'm using ElasticSearch to store listings. The user can sort by multiple fields (e.g. grossReturn, buyingPrice) etc.</p>
  
  <p>Now we want to offer the option, that the user can store favorite listings. </p>
  
  <p>Am storing the favorites in PostgresSQL. Then before each request I'm getting the favorites from Postgres - putting them in an array and have a scripted field like so:</p>
  
  <pre><code>const scripts = {
      favorite: {
        script: {
          source: 'return params.favorites.contains(params._source.id) ? 1 : 0',
          params: {
            favorites,
          },
        },
      },
    };
  </code></pre>
  
  <p>Now I also want to sort by this field and this is the problem:</p>
  
  <pre><code>const getSortParams = (sortBy, scripts) =&gt; {
    const sort = {};
  
    if (sortBy) {
      const fieldName = sortBy.split(',')[0];
      const sortOrder = sortBy.split(',')[1];
      if (fieldName === 'favorite') {
        sort._script = {
          type: 'number',
          script: scripts[fieldName].script,
          order: sortOrder,
        };
      } else {
        sort[fieldName] = {
          order: sortOrder,
        };
      }
    }
    return sort;
  };
  </code></pre>
  
  <p>It is very very slow - sorting taking roughly 3s. It makes sense since everything needs to be calculated.</p>
  
  <p>My question would be -> what is a better way to do this?</p>