Exploring Vue.js integration with Elasticsearch API functions

I have a script written in Vue.js and I am looking to incorporate an Elasticsearch API method.

// ./main.js
var Vue = require('vue');

Vue.use(require('vue-resource'));

import ES from './elasticsearch.js';

new Vue({

    el: 'body',

    methods: {
        search: function() {
            // need to implement calling the es.search method here...
        }
    }
});

Here is the Elasticsearch script for reference:

// ./elasticsearch.js
var es = require('elasticsearch');

var client = new es.Client({
  host: 'localhost:9200'
  ,log: 'trace'
});

client.search({
  index: 'my_index',
  type: 'my_type',
  body: {
    fields: {},
    query: {
      match: {
        file_content: 'search_text'
      }
    }
  }
}).then(function (resp) {
    var hits = resp.hits.hits;
}, function (err) {
    console.trace(err.message);
});

My goal is to call the client.search method within the search method in main.js and send the search text to my server. How can this be achieved? Is there a way to access and use the elasticsearch object within a vuejs method?

Any suggestions or guidance would be greatly appreciated!

Answer №1

your elasticsearch.js file needs to be properly configured as a module: import ES from './elasticsearch'. This code won't work because the file is not exporting anything.

A correct setup should resemble this:

// ./elasticsearch.js
var es = require('elasticsearch');

var client = new es.Client({
  host: 'localhost:9200',
  log: 'trace'
});

function search(myIndex, myType, searchText) {
    return client.search({
        index: myIndex,
        type: myType,
        body: {
            fields: {},
            query: {
                match: {
                    file_content: searchText
                }
            }
        }
    }).then(function(resp) {
        return hits = resp.hits.hits;
    }, function(err) {
        console.trace(err.message);
    });
}

export { search };

We have defined a function called search and exported it with proper return statements to handle Promise responses.

In your main.js file, you can import the function and use it like this:

// ./main.js
var Vue = require('vue');

Vue.use(require('vue-resource'));

import { search } from './elasticsearch.js';

new Vue({

    el: 'body',

    methods: {
        search: function() {
            var result = search('someindex', 'sometype', 'Search text here').then(function(res) {
                // do something with the result
            })
        }
    }
});

Answer №2

If the "resp.hits.hits" in your code represents the search result as a JSON Object Array, then you can set up your Vue instance like this:

// ./main.js
var Vue = require('vue');

Vue.use(require('vue-resource'));

import ES from './elasticsearch.js';

new Vue({

    el: 'body',
    data:{
       searchResults:[] //specifying that it is an array
    }

    methods: {
        search: function() {
           var self = this;
           // make the search and fetch response data
           client.search(function(resp){
                self.searchResults = resp.hits.hits
           })
        }
    }

});

Then, in your HTML, simply bind the DOM to searchResults.

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

Is there a way for a button to automatically delete its corresponding index in an array upon being clicked?

I am currently developing a multiple choice quiz where users can input their own questions and answers to create a quiz. I am facing an issue with allowing users to delete questions stored in the question bank. Here is what I have tried so far: bodyText ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

Node, Express, and Angular redirection problem encountered

I have a web application built with node, express, and angular. The app consists of two main pages - a user profile page and a login page. My goal is to redirect any user who is not logged in to the login page when they try to access the profile page. Howe ...

Generating charts using JSON data with the help of JavaScript

Hi there! I have a JSON file shown in the first image and I would like to create a chart similar to the one in the second image using JavaScript (using any library). Can anyone provide me with a simple example code on how to achieve this? ...

What is the best way to limit input to only numbers and special characters?

Here is the code snippet I am working with: <input style="text-align: right;font-size: 12px;" class='input' (keyup.enter)="sumTotal($event)" type="text" [ngModel]="field.value" (focusin)="focusin()" (focusout)="format()" (keyup.ente ...

Styling an exponential number in a table header using Vuetify

I am looking to replace the default header 'number' with a custom HTML header while using vuetify for displaying a data table. My current setup looks like this: headers: [ {text: 'number', value: &a ...

Tips for incorporating a time interval in every iteration of a for loop

I am attempting to display each word of a given text string on the screen at 60-second intervals. After some trial and error, here's what I have come up with: let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac di ...

What is the process for applying the source from an object while utilizing video-js?

I've been struggling to use a video player for streaming m3u8 videos. The code below works, but I want to dynamically set the source using an object. <video id="my-video" class="video-js" auto ...

I am able to see the Redux props showing up in Redux DevTools, but for some reason they are not

I am facing an issue where I am passing a Redux prop to a component that is fetched from a payload. The payload successfully updates the state in my reducer and the component receives the prop (an array of objects fetched in the action) according to my Red ...

Is Grouping Together Installed Private Modules Possible?

Exploring a modular JavaScript approach in my upcoming project is a new concept for me. I would prefer explanations to be simple due to my limited experience. I have uploaded my private package on npm: @name/package-name The private package contains mul ...

What is the best way to add an inset shadow with a transparent background in SVG?

I created a basic SVG Icon, but I'm having trouble adding an inset shadow effect to it. Is there a way to achieve this? svg { filter: drop-shadow(0.1px 1.5px 0.1px rgba(0,0,0,0.5)); } <!DOCTYPE html> <html> <body> <svg width ...

Use JSON data to populate a dynamic bar chart in Highcharts

As a beginner in parsing JSON objects to highcharts, I am trying to create a basic bar graph. I have managed to set up the title of the graph, but I am having trouble displaying the series that I want to show (count as series and qpAnswer as xAxis). Below ...

Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript? When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist&apo ...

Tips for retaining a chosen selection in a dropdown box using AngularJS

How can I store the selected color value from a dropdown box into the $scope.color variable? Index.html: <label class="item item-select" name="selectName"> <span class="input-label">Choose your favorite color:</span> <select id="colo ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

Unable to set DIV to 'inline-block' or none based on checkbox selection

Despite reviewing multiple examples, I am still struggling to make this DIV visible and hidden by clicking a checkbox. Can someone please review my JavaScript code? <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Conten ...

What could be causing the issue when attempting to run "npm run serve"?

Can anyone help me understand this error message and suggest a possible solution? Failed to compile. ./src/main.js Module build failed (from ./node_modules/eslint-loader/index.js): Error: No ESLint configuration found. at Config.getLocalConfigHierar ...

Using Angular to send JSON data to an API

I'm attempting to send JSON data to an API, but I'm encountering the following error... 405 (Method Not Allowed) Below is the JSON object I'm trying to send and the corresponding HTTP request... var productAttributes = { "CostRequire ...

How to Test React Js API Calls with Jest?

I'm currently in the process of writing test cases for my API call function, but I'm encountering difficulties as I am unable to successfully run my tests. Below is the code for the API call function and the corresponding test cases. export async ...

Utilize overlib text in your jQuery projects

As I develop my personal Grease Monkey userscript, I find myself in need of modifying the overlib text through the use of jQuery. Here's a representation of it in HTML code: <div class="expbar" onmouseover="return overlib('Some text',HA ...