3
votes

I've got a few thousands documents in my elasticsearch index. Document has a few nested collections. One of them is nested collecion of "variants". The JSON structure the one of documents is:

{
  "id" : 1,
  "name": "lollipop",
  "model_name": "candy",
  "variants": [
    {
      "id": 1000,
      "taste": "orange",
      "gross_price": 13,
      "stock_quantity": 15
    },
    {
      "id": 1001,
      "taste": "apple",
      "gross_price": 7,
      "stock_quantity": 1
    },
    {
      "id": 1002,
      "taste": "bannana",
      "gross_price": 9,
      "stock_quantity": 13
    },
    ,
    {
      "id": 1003,
      "taste": "pinaple",
      "gross_price": 19,
      "stock_quantity": 10
    },

    ... and more and more ...       

  ],
  ... and more and more ...
}

My shop on the one page show only 48 products. My index have total 4800 products so in my shop are 100 pages.

I have got a problem with sorting by price.

On the any page I want to get next 48 products with the lowest variants price where stock_quantity is greater than 1. For the lightest result - I'm using inner_hits by variants. Then I've got only that variants which have my conditions.

I write some elasticsearch query (for the first page):

GET myshop_index/product/_search
{
  "from": 0,
  "size": 48,
  "sort": [
    {
      "variants.gross_price": {
        "mode": "min", 
        "order": "asc",
        "nested_path": "variants"
      }
    }
  ], 
  "_source": {
    "excludes": [
      "variants"
    ]
  },
  "query": {
    "bool": {
      "filter": [
        {
          "nested": {
            "query": {
              "bool": {
                "must": [
                  {
                    "range": {
                      "variants.stock_quantity": {
                        "gt": 1
                      }
                    }
                  }
                ]
              }
            },
            "path": "variants",
            "inner_hits": {
              "name": "variants",
              "size": 10000
            }
          }
        }
      ]
    }
    }
  }
}

I've got first 48 products with their variants but this sorting working not on full of products variants in my index. This sorting works like:

  1. get first 48 products with variants
  2. sort variants price asc
  3. return result

But I need to get this scenario:

  1. sort all products variants in my index by gross_price ascending
  2. return first 48 products with their variants (using inner_hits) sorted by gross_price ascending.

Any ideas?

1

1 Answers

1
votes

Ok, I resolved my problem. I found the Nested Sorting . It's work for me. Especially 5th point of this. "The nested_filter in the sort clause is the same as the nested query in the main query clause. The reason is explained next." and explain after that