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

TypeScript disregards interface method argument types

Unexpectedly, the code below compiles without any errors (using tsc 3.9.5): interface IDateHandler { handleDate: (Date) => void; } let dateHandler: IDateHandler = { handleDate: (d: Date) => {}, }; dateHandler.handleDate([1, 2, 3]); Even more s ...

Exploring the communication between two components in Angular 2

My Angular components include: Create-Articles: used for creating articles. List Articles: utilized for listing all articles. The parent component is the Home Component. import { Component, OnInit } from '@angular/core'; @Component({ ...

Angular2 Cache: Enhance Your Application's Performance

Currently seeking a cache solution for my Angular2 application. Imagine we have a massive collection of Movie objects stored on a server, too many to fetch all at once. The server offers a REST endpoint: getMovie(String id) On the client side, I need a s ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

Displaying a disabled div depending on the dropdown selection in Angular Material

My goal is to display filters in a dropdown after they have been selected. Currently, I have static disabled divs and a dropdown where filters can be selected. This is the dropdown: <mat-form-field> <mat-label>{{ 'supplier.showFilters&a ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback. public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void { ...

Enhance the visual appeal of your checkboxes in React Fluent UI by customizing the color of the checked mark and

I have a React application using Fluent UI. Currently, the <Checkbox/> component is displaying with its default colors and behavior like this: I want to customize the color of the checked mark and label (Green for checked mark and brown for label). ...

Retrieve an array of information and convert it into an object using Angular

My previous data is displaying correctly in the chart, as shown below: @Component({ selector: 'app-inpout-bar-chart', templateUrl: './inpout-bar-chart.component.html', styleUrls: ['./inpout-bar-chart.component.scss'] }) exp ...

Navigate to a nested page in React router and automatically open a new page whenever there are parameters passed

I am currently using create-react-app to build my project and I am working on implementing dynamic routing. My site has three main pages: Accordion, Movies, and MovieDetail. The Movies page displays a list of movies fetched from swapi. The goal is to have ...

How to access the component instance in Angular through router events

I am currently working on incorporating a title service into my Angular 10 application. My goal is to subscribe to router events, access the activated route's component, check if it has a title() getter, and then use that information to set the page&a ...

Building TypeScript Model Classes

Greetings! As a newcomer to TypeScript with a background in both C# and JavaScript, I am on a quest to create class models resembling those found in C#. Here's my attempt so far: export class DonutChartModel { dimension: number; innerRadius: ...

Working with Yarn and Webpack: Incorporating a TypeScript .ts file from an external Node directory not controlled by Yarn/Webpack

I am currently working on a k6 project for load testing, utilizing Yarn and Webpack. This project is stored within a sub-folder of a larger repository that primarily uses npm Node modules. My goal is to access a secret from AWS's Secrets Manager in t ...

Is it possible to alter the background color once the content of an input field has been modified?

I am working with an angular reactive form and I want to dynamically change the background color of all input fields when their value is changed. Some of these input fields are pre-populated and not required. I came across a potential solution on Stack Ove ...

Guide to aligning a fraction in the center of a percentage on a Materal Design progress bar

Greetings! My objective is to create a material progress bar with the fraction displayed at the top of the percentage. Currently, I have managed to show the fraction at the beginning of the percentage. Below is the code snippet: <div class=" ...

Utilizing a variable string name for a method in Typescript Vue

My objective is to trigger a different function based on the value of a variable. However, when working in VS Code, I receive an error message that states: 'method' implicitly has a type of 'any' because 'type1Func' and &apos ...

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...

Receiving errors in React/TS/material-ui when attempting to use a variable as a value for a grid property. Messages include "No overload matches" and "Type 'number' is not assignable to type..."

tl;dr: When using a variable as the value of a grid xs property in JSX, material-ui throws a TS error. I'm working on implementing grids in material-ui with React/TypeScript. The goal is to make the width of a specific element dependent on the quant ...

What is the best way to utilize TypeScript module augmentation with material-ui components?

I have gone through the answers provided in this source and also here in this link, but it appears that they are outdated. I attempted to enhance the type definition for the button component in various ways, including a separate typings file (.d.ts) as we ...

Establish a table containing rows derived from an object

I am currently dealing with a challenge in creating a table that contains an array of nested objects. The array I have follows this schema: array = [ { id: 'Column1', rows: { row1: 'A', row2 ...