# ElasticSearch JAVA create custom sort in place of attribute value sort

**URL:** <https://discuss.elastic.co/t/elasticsearch-java-create-custom-sort-in-place-of-attribute-value-sort/354982>\
**Category:** Elasticsearch\
**Created:** [March 7, 2024, 8:38pm UTC](https://discuss.elastic.co/t/elasticsearch-java-create-custom-sort-in-place-of-attribute-value-sort/354982 "2024-03-07T20:38:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Manoj\_Upadhyay](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/manoj_upadhyay/32/60156_2.png) [@Manoj\_Upadhyay](https://discuss.elastic.co/u/Manoj_Upadhyay)\
**Post date:** [March 7, 2024, 8:38pm UTC](https://discuss.elastic.co/t/elasticsearch-java-create-custom-sort-in-place-of-attribute-value-sort/354982/1 "2024-03-07T20:38:17Z")

</div>

For example, I have 6 accounts (1,2,34,5,6)of transactions in index and I want to search transactions and sort by order by account 4,6,3,2,1,5(custom order ) then how I can use it .

```auto
SearchResponse<MyClass> esResponse = esClient.search((s -> s
                 .index("loans")
                 .size(pageSize)
                 .from(page)
                 .query(q -> q
                     .terms(t -> t
                         .field("ic_number.keyword")
                         .terms(tqf -> tqf.value(/* List<String> here */))
                     )
                 ).sort(so -> so
                     .field(FieldSort.of(f -> f
                         .field("date_created")
                         .order(SortOrder.Desc)
                     ))
                 )
             ), MyClass.class);

```

---

<div class="post-metadata">

**Author:** ![TimV](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/timv/32/13162_2.png) [@TimV](https://discuss.elastic.co/u/TimV)\
**Post date:** [March 8, 2024, 6:20am UTC](https://discuss.elastic.co/t/elasticsearch-java-create-custom-sort-in-place-of-attribute-value-sort/354982/2 "2024-03-08T06:20:47Z")

</div>

How is that sort order defined? That is, how do you know that `6` comes between `4` and `3`?

Your options are probably going to come down to

- Use a [scripted sort](https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#script-based-sorting)
- Use a runtime field
- Sort on the client

---

<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:** [April 5, 2024, 6:20am UTC](https://discuss.elastic.co/t/elasticsearch-java-create-custom-sort-in-place-of-attribute-value-sort/354982/3 "2024-04-05T06:20:49Z")

</div>

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