How can Laravel integrate Elasticsearch to retrieve documents based on multiple categories?

After successfully implementing the code snippet below to retrieve blog posts based on a query, I encountered an issue when attempting to fetch documents that match specific categories.

$params = [
        'index' => 'blog',
        'type' => 'post',
        'body' => [
            'query' => [
                'multi_match' => [
                    'query' => $request->get('query'),
                    'fields' => ['title', 'description']
                ]
            ]
        ]
    ];
    $response = \Elasticsearch::search($params); // functioning correctly
    

I attempted to modify the code above by including a variable $categories in order to retrieve documents matching any of the specified category values selected from checkboxes.

The $categories variable contains values received from checkboxes.

Despite my efforts, the amended code provided below returned empty results:

// $categories = $request->get('categories');
$categories = ["News", "Technology"];
$params = [
        'index' => 'blog',
        'type' => 'post',
        'body' =>  [

            "query"=> [
                "filtered"=> [
                    "query"=> [
                        "match_all"=> []
                    ],
                    "query"=>[
                        "terms"=> [
                            "category"=> $categories
                        ]
                    ]

                ]
            ]
        ]
    ];

$response = \Elasticsearch::search($params); // zero hits returned

If you have any suggestions on how I can adjust the code to retrieve documents based on one or more categories instead of keywords, it would be greatly appreciated.

Answer №1

Two query clauses are found at the same level within the filtered clause, which is not permitted.

"query"=> [
                    "filtered"=> [
                        "query"=> [  <-- (1)
                            "match_all"=> []
                        ],
                        "query"=>[ <-- (2)
                            "terms"=> [
                                "category"=> $categories
                            ]
                        ]

                    ]

If your intention is to query only the categories, then you should eliminate the first clause. The revised query would look like this:

                  "query"=> [
                    "filtered"=> [
                        "query"=>[
                            "terms"=> [
                                "category"=> $categories
                            ]
                        ]
                     ]  
                    ]

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

Adding several entries into mysql with the assistance of php

I've been attempting to input multiple records into my database table, but every time I try, all I see are zeros(0) inserted into the fields. Here's what I attempted: I used a foreach loop for insertion, but unfortunately it doesn't seem to ...

Submitting a page with PHP, Ajax, and JSON

Need help with making an Employee search functionality in my business using Ajax. After submitting the form, I want to load employee details using jQuery-based Ajax. Here is the code for searching employees. The problem I'm facing is that after submi ...

Communicating between PHP chat client and server

Currently, I am developing a basic PHP web chat application that interacts with a MySQL database. The communication is facilitated through AJAX requests - when a user posts a message, it gets saved in the database. function sendData(){ var textData = $(& ...

Tips for exchanging JSON data between HTML and PHP using jQuery Ajax?

Hello there! I am just starting to learn PHP and jQuery, and I have been experimenting with some code to understand how things work. However, I seem to be having issues with sending data back and forth between my webpage and the PHP file on the server. Her ...

Tips for accelerating the loading of data retrieved through ajax requests

At present, data is being fetched in array form from a PHP script. I have noticed that when retrieving 40 sets of data, it takes approximately 20 seconds for the data to load. This delay may be due to ajax having to wait until all the results are gathered. ...

Is there a way in PHP to increase the quantity by 1 if the value is present in the array?

I want to update the quantity in the session cart or add a new item if it doesn't already exist. If the item is already in the cart, I am looking to increase the quantity by 1. if (!isset($_SESSION['cart'])) { $item = array('pid&ap ...

PHP seems to be resistant to receiving data from ajax requests

I am attempting to develop a drag and drop file upload feature without using a traditional form, utilizing JavaScript's FormData. However, I am encountering an issue where PHP does not seem to be receiving the uploaded file. Could there be some missin ...

What is the best way to send information from a main blade to an included modal?

Trying to implement a functionality where a modal is triggered on clicking a button and an array named $incident is passed through to the properties of a Vue component. What is the correct way to pass data from a parent blade to an included modal? I initia ...

The statusText variable for getXMLHTTP object is not found when the status is not equal to

Earlier, I posted about this issue before isolating the problem. Now that I have isolated it, I wanted to repost with a clearer focus on the two functions causing the problem. Whenever I update my State, it triggers the getCity function. The call is being ...

Can you provide step-by-step instructions on how to construct phpalanger phpc

Attempting to compile https://github.com/DEVSENSE/Phalanger, but encountering build errors after the process. Could it be due to using VS 2015, possibly a version compatibility issue? https://i.stack.imgur.com/Q6qXv.png ...

Attention! Are you aware of the potential consequences of the impending phase-out of the name attribute in W3C validation? Have you considered how this development

Any thoughts on what could replace the name attribute? According to the W3C validator... Validation Output: 4 Warnings Here is a list of the warning message(s) generated while checking your document. Warning Line 12, Column 21: The name attribute i ...

Sophisticated method for grouping multi-dimensional array elements by their key indices

How do I calculate the total value of all child elements within this array structure? [0] => Array ( [value] => ? // 8590.25 + 200.5 + 22.4 [children] => Array ( [0] => Array ...

What steps should I take to resolve the issue with the Error: spawn php-cgi ENOENT?

My current setup involves Nuxt with php-express, and I've been troubleshooting a persistent error in my php script for hours without success. *server.cjs : * const express = require("express"); const expressPhp = require("express-php&q ...

Looping through mysql data horizontally within a div tag

Looking for assistance to create a content loop similar to the one on this website? I attempted to use a while() loop, but it ended up displaying vertically without using a table. I suspect this page utilizes thumbnails. What I aim for is to have the it ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

The mysql database connection experiences failure after an ajax request is made

I've encountered an issue with a function that connects to MySQL DB. It works perfectly in a "normal" call, but fails to connect when triggered by an AJAX call. Here is the PHP code snippet: // Return data for ShowDdl() function getDDLdata($tabl ...

PHP - The memory limit has been exceeded with 134217728 bytes allocated

Here is a snippet of code that I'm currently working with: <?php namespace Debug; function Alert($msg){ $temp = "<script>alert('".$msg."')</script>"; echo $temp; } function Log($msg){ $temp = "<script>consol ...

Center an image vertically in an AdminLte content-wrapper division

I am currently utilizing an AdminLte template as the framework for my design. In the designated area where I need to insert the main content, it is structured in the following manner: <div class="content-wrapper"> <se ...

Eliminate self-closing elements in XPath

I recently came across a helpful solution to eliminate empty tags from my XML file. If you're interested, you can find the solution here. However, I've encountered an issue with this approach when dealing with nested nodes that are empty. Take ...

CSRF verification for Laravel Commands was unsuccessful

There seems to be an issue I'm encountering while using cron for a Laravel Command. When the function is executed as php /path/to/artisan/ command:cron, it leads to an error stating CSRF verification failed. Has anyone found a solution to disabling C ...