# Random\_score выборка

**URL:** <https://discuss.elastic.co/t/random-score/163897>\
**Category:** Вопросы на русском языке\
**Created:** [January 11, 2019, 12:08pm UTC](https://discuss.elastic.co/t/random-score/163897 "2019-01-11T12:08:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mishut](https://avatars.discourse-cdn.com/v4/letter/m/71c47a/32.png) [@mishut](https://discuss.elastic.co/u/mishut)\
**Post date:** [January 11, 2019, 12:08pm UTC](https://discuss.elastic.co/t/random-score/163897/1 "2019-01-11T12:08:32Z")

</div>

Доброго времени суток.  
Начал изучать эластик и столкнулся с проблемой.  
Мне надо выбрать случайно 5 записей, но с условием, что определенное поле (type\_id) в индексе этих записей должны быть разные. Если не получается найти 5 записей с таким условием, то находить столько, сколько получилось.

Спасите помогите пожалуйста ))

```
        $response = $this->client->search([
        'index' => 'addresses',
        'type' => 'address',
        'body' => [
            '_source' => ['id', 'type_id'],
            'size' => 5,
            'query' => [
                'bool' => [
                    'must' => array_merge(
                        [
                            ['function_score' => [
                                'random_score' => [
                                    'seed' => [session()->getId(), request()->path()],
                                ]
                            ],
                            ]
                        ],
                        [
                            ['term' => ['published' => '1']],
                        ],
                        array_filter([
                            $city ? ['term' => ['city_id' => $city->id]] : false,
                        ])
                    ),
                ],
            ],
        ],
    ]);

```

По сути есть вариант использовать aggs, но в таком случае невозможно (или я не умею) сделать random\_score с использованием seed. Выборка впоследствии отображается на сайте в виде перелинковки и использование random\_score позволяет сделать так, чтобы при обновлении странички выборка не изменялась.

---

<div class="post-metadata">

**Author:** ![Igor\_Motov](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/igor_motov/32/45193_2.png) [@Igor\_Motov](https://discuss.elastic.co/u/Igor_Motov)\
**Post date:** [January 11, 2019, 3:33pm UTC](https://discuss.elastic.co/t/random-score/163897/2 "2019-01-11T15:33:07Z")

</div>

> [@mishut](#):
>
> По сути есть вариант использовать aggs, но в таком случае невозможно (или я не умею) сделать random\_score с использованием seed.

Возможно, только надо бакеты тоже случайно отсортировать. Пара способов приходит в голову:

```auto
PUT testidx
{
  "mappings": {
    "doc": {
      "properties": {
        "type_id": {
          "type": "keyword"
        }
      }
    }
  }
}

PUT testidx/doc/1
{
  "type_id": "A"
}

PUT testidx/doc/2
{
  "type_id": "A"
}

PUT testidx/doc/3
{
  "type_id": "A"
}

PUT testidx/doc/4
{
  "type_id": "B"
}

PUT testidx/doc/5
{
  "type_id": "B"
}

PUT testidx/doc/6
{
  "type_id": "C"
}

# By generating random bucket order
POST testidx/_search
{
  "query": {
    "function_score": {
      "random_score": {
        "seed": 123456789
      }
    }
  },
  "size": 0,
  "aggs": {
    "types": {
      "terms": {
        "field": "type_id",
        "size": 5,
        "script": {
          "source": "(_value + '1234567891').hashCode() + '_' + _value",
          "lang": "painless"
        },
        "order": {
          "_key": "asc"
        }
      },
      "aggs": {
        "hits": {
          "top_hits": {
            "size": 1
          }
        }
      }
    }
  }
}

# By using max record score
POST testidx/_search
{
  "query": {
    "function_score": {
      "random_score": {
        "seed": 123456789
      }
    }
  },
  "size": 0,
  "aggs": {
    "types": {
      "terms": {
        "field": "type_id",
        "size": 5,
        "order": {
          "max_score": "asc"
        }
      },
      "aggs": {
        "hits": {
          "top_hits": {
            "size": 1
          }
        },
        "max_score": {
          "max": {
            "script": "_score"
          }
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [February 8, 2019, 3:33pm UTC](https://discuss.elastic.co/t/random-score/163897/3 "2019-02-08T15:33:12Z")

</div>

Closed on February 8, 2019, 3:33pm UTC

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