Trouble with query. Tough calculation

This is my current query

{
  query: {
    function_score: {
      functions: [
        { filter: { match: { foo: "top" } }, weight: 2.0 },
        { filter: { match: { foo: "mid" } }, weight: 1.0 },
        { field_value_factor: { field: "bar.a", missing: 0 } },
        { field_value_factor: { field: "bar.b", missing: 0 } },
        { field_value_factor: { field: "bar.c", missing: 0 } }
      ],
      score_mode: "sum",
      query: {
        filtered: {
          filter: {
            bool: {
              filter: [{ terms: {"bar": ["a", "b", "c"]} }]
            }
          }
        }
      }
    }
  }
}

which currently is creating a score by adding either 2.0 or 1.0 depending on foo, and also adding the fields of each of the object children of bar. This works fine.

It's essentially foo + bar.a + bar.b + bar.c

What I'd like to do is this calculation instead:
foo * ( bar.a + bar.b + bar.c )

I'm not sure how to structure the query to achieve this. Maybe there should be a subquery that calculates the children of bar with score_mode: "sum", and then wrap that somehow with the filter weighting of foo and multiply? What is the syntax to do that?

Also, I know that filtered queries are deprecated, but when I change it to bool, it comes out with a different calculation.

Any help would be amazing. Thank you.

It's not elegant, but I think you'll have to do a function_score inside a function_score. Something like:

{
  "query: {
    function_score: {
      functions: [
        { filter: { match: { foo: "top" } }, weight: 2.0 },
        { filter: { match: { foo: "mid" } }, weight: 1.0 },
        { filter: {
          function_score: {
            functions: [
              { field_value_factor: { field: "bar.a", missing: 0 } },
              { field_value_factor: { field: "bar.b", missing: 0 } },
              { field_value_factor: { field: "bar.c", missing: 0 } }
            ],
            score_mode: "sum"
          }
        } }
      ],
      score_mode: "multiply",
      query: {
        bool: {
          filter: {
            bool: {
              filter: [{ terms: {"bar": ["a", "b", "c"]} }]
            }
          }
        }
      }
    }
  }
}

Note: haven't tested this, just writing off top of my head :slight_smile:

Basically, sum up a/b/c first, then multiply that score by foo.mid and foo.top.

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