Search code examples
elasticsearchelasticsearch-dslelasticsearch-7

How can I find documents which match all words in differents queries?


For example with this mappings:

PUT /unit-test
{
  "mappings": {
    "properties": {
      "name": { "type": "text" },
      "landlords": {
        "type": "nested", 
        "properties": {
          "name": { "type": "text" }
        }
      }
    }
  }
}

If I have this document:

{ 
  "name": "T2 - Boulevard Haussmann - P429",
  "landlords": [
    { "name": "John Doe" }
  ] 
} 

I want "boulevard hausmann" and "boulevard haussman doe" to match but not "rue haussman" or "haussman jeanne".

I cannot use multi_match with "operator": "and" because landlords are nested.


Solution

  • An idea is to set the copy_to mapping parameter to the name and landlords.name fields, in order to copy the values of both fields into another field (say, names) that you will use for your search.

    So your mapping may look like:

    {
      "mappings": {
        "properties": {
          "name": {
            "type": "text",
            "copy_to": "names"
          },
          "landlords": {
            "type": "nested",
            "properties": {
              "name": {
                "type": "text",
                "copy_to": "names"
              }
            }
          },
          "names": {
            "type": "text"
          }
        }
      }
    }
    

    and your search

    {
      "query": {
        "match": {
          "names": {
            "query": "boulevard haussman doe",
            "operator": "AND"
          }
        }
      }
    }