PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to do multiple "match" or "match_phrase" values in ElasticSearch

 October 24, 2022     elasticsearch     No comments   

Issue

So ElasticSearch has the terms query, which lets me supply multiple values and return a ist of documents where field X matches any of those values.

But I want to do the same thing with match_phrase - i.e. return documents where field X contains a case insensitive match for a term with spaces. I currently do it my using an or filter (see below). But that seems like a very verbose way of doing what I want, considering that terms does something similar already.

Current method

It seems ridiculous that a query searching a single field for one of three values should be 33 lines long.

{
  "query": {
    "filtered": {
       "filter": {
           "or": {
              "filters": [
                 {
                     "query": {
                         "match_phrase": {
                            "myField1": "My first search phrase"
                         }
                     }
                 },
                 {
                     "query": {
                         "match_phrase": {
                            "myField1": "My second search phrase"
                         }
                     }
                 },
                 {
                     "query": {
                         "match_phrase": {
                            "myField1": "My third search phrase"
                         }
                     }
                 }
              ]
           }
       }
    }
  }
}

Solution

After a long night trying to figure this out myself I came up with this:

"query" : {
        "bool": {
            "should": [
               {
                   "match_phrase": {
                      "myField1": "My first search phrase"
                   }
               },
               {
                   "match_phrase": {
                      "myField1": "My second search phrase"
                   }
               }
            ]
        }
    }

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html



Answered By - Jonathon Cwik
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing