Guide on obtaining Elastic search documents in the specified order of identifiers

Given a specific order of document IDs [1, 4, 2, 5] and some filtering criteria { match: {...} }, what is the most efficient method to ensure that the resulting documents are retrieved in the desired order [1, 4, 2, 5]?

Here is an example of a sample document:

{
    "id": <uuid>,
    "name": "Some name",
    "description": "Some description"
}

I am aware that Elasticsearch stores _id for each document and that the id field within my document aligns with this.

Therefore, I would like to provide an array of IDs and retrieve the results in that specified order after applying all necessary filters.

For instance, suppose I have the following 4 documents:

{
    "id": "abcd",
    "name": "test1",
    "description": "test1"
},
{
    "id": "bcde",
    "name": "test2",
    "description": "test2"
},
{
    "id": "cdef",
    "name": "test3",
    "description": "test3"
}

If I have an array of IDs ["cdef", "abcd", "bcde"], I would like to query Elasticsearch and receive the results in the specified order, meaning the document with the ID "cdef" should appear first in the hits, followed by "abcd" and then "bcde".

Answer №1

This particular approach involves using a script for sorting. The idea is to provide an array of terms along with their corresponding score values, and the script will assign the appropriate score to the document when it matches the specified ID.

{
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": """for (int i = 0; i < params.scoring.length; i++) { if(doc['id.keyword'].value ==  params.scoring[i]['id']) return params.scoring[i]['score']; } return 0;""",
        "params": {
          "scoring": [
            {
              "id": "cdef",
              "score": 1
            },
            {
              "id": "abcd",
              "score": 2
            },
            {
              "id": "bcde",
              "score": 3
            }
          ]
        }
      },
      "order": "asc"
    }
  },
  "query": {
    "terms": {
      "id": [
        "cdef",
        "abcd",
        "bcde"
      ]
    }
  }
}

Answer №2

One solution is to implement a script similar to the following:

{
    "sort": {
        "_script": {
            "type": "number",
            "script": {
                "source": "params.get(doc._id.value);",
                "params": {
                    "5c357c0eb565e654fcc3507c": 0,
                    "5c3539f1b565e632d1c690ee": 1
                },
                "lang": "painless"
            },
            "order": "asc"
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using TypeScript, a typed interface will not permit a value that is not within its specified string literal type

I have downsized my issue to a smaller scale. This class needs to set the default value of its "status" property. The type T extends the string literal type "PossibleStatus" which consists of 3 possible strings. Typescript is giving me trouble with this. ...

Adjusting the Material UI Select handleChange function

const handleObjectChange = (event: React.ChangeEvent<{ value: unknown }>) => { const { options } = event.target as HTMLSelectElement; const selectedValues: object[] = []; for (let i = 0, l = options.length; i < l; i += 1) { if ...

Strategies for splitting a component's general properties and accurately typing the outcomes

I am attempting to break down a custom type into its individual components: type CustomType<T extends React.ElementType> = React.ComponentPropsWithoutRef<T> & { aBunchOfProps: string; } The code appears as follows: const partitionProps = ...

Issue with React hook forms and shadcn/ui element's forwardRef functionality

Greetings! I am currently in the process of creating a form using react-hook-form along with the help of shadcn combobox. In this setup, there are two essential files that play crucial roles. category-form.tsx combobox.tsx (This file is utilized within ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...

Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code: import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; import {Observable} from 'rxjs' ...

Using Lodash to Substitute a Value in an Array of Objects

Looking to update the values in an array of objects, specifically the created_at field with months like 'jan', 'Feb', etc.? One way is to loop through using map as demonstrated below. However, I'm curious if there's a more co ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

react state change not triggering re-render of paragraph

I recently started learning react and web development. To streamline my work, I've been using ChatGPT, but I'm facing an issue that I can't seem to solve. I'm trying to fetch movie descriptions from the TMDB API using movie IDs, but des ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...

What is the process for transforming a multi-dimensional array containing strings into a multi-dimensional array containing numbers?

I've got a unique structure of data composed of arrays with strings as seen below: [ 0: Array(1) 0: Array(6) 0: [5.379856, 43.252967] 1: [5.422988, 43.249466] 2: [5.425048, 43.245153] 3: [5.383804, 43.239 ...

Comparing strings with data in objects using Angular

all. I have a query. What is the optimal method for comparing data? For instance, if you have a constant response = 225235743; And I aim to locate and exhibit all data in an object with the same ID as the one in this response. This needs to be resolved ...

Endure the class attribute in Angular 5

My SearchComponent has a route (/search) and SearchDetailComponent has a route (/search-detail:id). In the SearchComponent, there is a searchbox (input field) where I can type any text to start a search. After loading the search results and navigating to ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

What is it about Kyle Simpson's OLOO methodology that seems to swim against the tide of Typescript's popularity?

Disclaimer: this post might come across as impulsive. Warning for Typescript beginners! Also, a bit of a vent session. Recently, I delved into the OLOO approach from the YDKJS book series within a Typescript and Node environment. // ideal JS syntax le ...

Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions? In the TS 2.8 release notes, we see examples like: type ReturnType<T> = T exten ...

A solution to the error message "Type 'unknown' is not assignable to type 'Country[]' in React TypeScript" is to explicitly define the type of the

I encountered error TS2322: Type 'unknown' is not assignable to type 'Country[]' pages/Countries/index.tsx Full code: import * as ApiCountries from '../../services/APIs/countries.api' function Countries() { const findCo ...