A guide to transforming an object into a JSON query using Elasticsearch

Currently, I am developing a Search Application using Angular7 and elasticsearchJS. Within my data Service, the elasticsearch JSON query body is generated from user inputs. While it functions properly with a simple string query in this.query, there seems to be an issue with handling a complex array from this.selectedTopics (checkbox selections).

https://i.sstatic.net/xTTx0.png

The problem arises as backslashes appear in my console.log output when viewing the query (refer to image).

console.log(this.selectedTopics);

  // Output of selectedTopics:
  //  ["Lindenholz", "Sandstein"]

  this.selectedTopics.forEach( (item) => {
      this.termarray.push('{ "term": {"79_material":"' + item + '"}}');
  });

  console.log(this.termarray.join(', '));

    // Output of termarray:
    //
    //  [
    //      { "term": {"79_material":"Sandstein"}},
    //      { "term": {"79_material":"Lindenholz"}}
    //  ]
    // The formatting appears correct in the console, but sending termarray to the JSON body results in incorrect backslashes.

  this.body = {
    'size': '100',
    'from': '0',
    'query': {
      'filtered': {
        'query' : {
            'multi_match': {
                'query': this.query,
                'type': 'phrase_prefix',
                'fields': this.selectedCategory
            }
        },
        'filter': {
            'bool': {
                'must': [
                  this.termarray.join(', ')
                ]
            }
        }
    }
    },
    'facets' : {
      '79_material' : {
        'terms' : {'field' : '79_material.keyword'}
     },
      '79_technik' : {
        'terms' : {'field' : '79_technik.keyword'}
    },
      '79_kuenstler' : {
        'terms' : {'field' : '79_kuenstler.content'}
    },
    '79_verortung' : {
      'terms' : {'field' : '79_verortung.content'}
  },
  },
    'sort' : [
      { '79_material' : {'order' : 'asc'}},
      '_score'
  ]
  };

https://i.sstatic.net/mPv3S.png

The desired result should resemble:

[
{'term' : { '79_material': 'holz' }},
{'term' : { '79_material': 'lindenholz' }}
]

Answer №1

Have you experimented with this?

this.termarray.push({ term: { '79_material': item }});

(or you can also try:

this.termarray.push({ 'term': { '79_material': item }});
this.termarray.push({ 'term': { "79_material": item }});
this.termarray.push({ "term": { "79_material": item }});

)

LATEST UPDATE:

The instructions are a bit unclear regarding how termarray is managed, but what if you directly insert the items into body:

let termarray = this.body.query.filter.bool.must;
this.selectedTopics.forEach( (item) => {
    termarray.push({ term: { '79_material': item }});
});

SECOND UPDATE:

Below is a screenshot from Chrome post executing the second update:

https://i.sstatic.net/0AcSJ.png

Note that when you use JSON.stringify(body), the result is as expected without any backslashes.

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

AngularJS grid designed to emulate the functionalities of a spreadsheet

I have been facing challenges with Angular while attempting to recreate a spreadsheet layout in HTML using ng-repeat. Despite extensive research, I have not found a solution. My goal is to display data in a table format as shown below: <table> & ...

How can you retrieve the user that is currently signed in using AngularFire and Firebase Authentication in Angular?

If you're working with Angular and trying to access the currently signed-in user through Firebase Auth, you may encounter some difficulties. Here's a snippet of code provided in the Firebase Auth documentation that demonstrates how to get the sig ...

Tips for integrating an XML file into an Android layout view

I have an XML file containing Android UI on my device and I would like to read this file in my app. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" ...

Steps for eliminating the chat value from an array tab in React

tabs: [ '/home', '/about', '/chat' ]; <ResponsiveNav ppearance="subtle" justified removable moreText={<Icon icon="more" />} moreProps={{ noCar ...

What is the proper approach for returning JSON in a Rails GET request?

As an illustration when making a request GET --> http:://{url}?search={username} I must provide: [ {id: 1, name: 'sande', nickname: 'username'}, {id: 2, name: 'sande2', nickname: 'username'} ] This is how ...

Lucene only triggers the operation once the service has been disconnected

While attempting to update the lucene index with IndexWriter, I am utilizing IndexWriter.deleteDocument() and IndexWriter.updateDocument(). Oddly enough, after committing and closing the Writer, the changes do not seem to appear in search results until I ...

Error encountered while trying to access OData feed in Tableau 8.1 due to incorrect OData format

Having difficulty connecting to an OData feed, I keep receiving this error message: "Bad OData Format. Ensure you are using a URL that directs to a valid OData Source." I am able to access the URL in a browser (and receive the correct JSON response), and ...

Utilize TypeScript function types in React for enhanced functionality

I have made the decision to refactor a project that was originally created with vanilla JavaScript and now I want to transition it to TypeScript. One issue I am facing is how to pass a function as a type on an interface. Although I referred to the TypeScr ...

Getting JSON object string in Node.js using Express

I am currently utilizing Polymer's <iron-ajax> to send data, in the form of a JSON string created using JSON.stringify, to a Node Express server. However, upon receiving the data, it appears in a strange format that I am unable to parse. Specifi ...

Utilizing an AngularJS factory to retrieve JSON data from the server

I have a large JSON object in my controller that I want to move to a separate file. Currently, this is how I'm approaching it: myApp.controller('smController', ['$scope', function($scope) { ... var stadtmobilRates = { cla ...

Every time I attempt to implement a from_json and to_json on a custom struct, I encounter a linking issue

I designed a struct: { unsigned int id; std::string name; unsigned int maxPlayers; unsigned int numOfQuestionsInGame; unsigned int timePerQuestion; unsigned int isActive; } RoomData; Within my code, ...

Implement Angular and RxJS functions sequentially

this.functionalityClient.activateFeature(featureName) .pipe( concatMap( feature => { this.feature = feature; return this.functionalityClient.setStatus(this.feature.id, 'activated'); } ), con ...

Combining two JSON responses using AngularJS

$scope.addUserJson = $scope.adduser; console.log($scope.addUserJson); Output Object {"username":"Mik911","firstname":"Mike","lastname":"Angel","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563b3f3d16313b373f3a78353 ...

In JavaScript, combine two arrays of equal length to create a new array object value

Trying to figure out how to merge two arrays into a new object in JavaScript var array1 = ['apple', 'banana', 'orange']; var array2 = ['red', 'yellow', 'orange']; If array1[0] is 'apple&apos ...

What is the best way to organize and store multiple 2D arrays of test data in a properties file for easy access during testing?

I want to store all the test data either in a properties file or a JSON file since they are more readable than an XML. I am considering using a single properties file to store data for the entire project. I'm not sure if this is feasible. I am utiliz ...

Creating a chart with multiple series in canvas js through looping

I'm currently working on creating a multi-series chart using Canvasjs. I've encountered an issue where I can't include a loop inside the dataPoints and have had to manually code everything. Is there a way to utilize for loops in this scenari ...

Is it possible to utilize an InterleavedBufferAttribute for index values?

I am troubleshooting a code snippet that is throwing an error: const geometry = new THREE.BufferGeometry(); const indices = new THREE.InterleavedBufferAttribute(...); geometry.setIndex(indices); // this is invalid After running this code, I receive a com ...

Iterate through a JSON object to tally occurrences of identical values across multiple arrays

I need to iterate through a JSON object and tally the occurrences of elements with identical values in different arrays. Here is an example of my object: var testconn = {"_total": 3, "values": [ { "articlesRead": [ ...

Modifying the nginx configuration file for an Angular application: a step-by-step guide

After deploying my Angular application on an nginx server, I encountered a problem. When I accessed http://**.8.100.248:30749, it displayed the default index.html page from the nginx server instead of my actual application located in the html folder under ...

Remove null or empty key-value pairs from a JSONObject

My JSON File Looks Like This: { "models":{}, "path":[ { "path":"/web-profiles", "operations":[ { "type":"", "responseMessages":[] } ] } ], " ...