Avión
Avión

Reputation: 8396

Search in two different types with different mappings in Elasticsearch

Having the following mapping of the index tester with two types items and items_two:

curl -XPUT 'localhost:9200/tester?pretty=true' -d '{
  "mappings": {
      "items": {
         "properties" : {
           "body" : { "type": "string" }
}},
      "items_two": {
         "properties" : {
           "body" : { "type": "string" },
           "publised" : { "type": "integer"}
}}}}'

I put three elements on it.

curl -XPUT 'localhost:9200/tester/items/1?pretty=true' -d '{
     "body" : "Hey there im reading a book"
}'

curl -XPUT 'localhost:9200/tester/items_two/1?pretty=true' -d '{
     "body" : "I love the new book of my brother",
     "publised" : 0
}'

curl -XPUT 'localhost:9200/tester/items_two/2?pretty=true' -d '{
     "body" : "Stephen kings book is very nice",
     "publised" : 1
}'

I need to make a query that matches the word book and has published = 1 AND the ones that has not published on the mapping, but has book on it (as the only item of items).

With the following query I only get match with the "Stephen kings book is very nice" item (obviously).

curl -XGET 'localhost:9200/tester/_search?pretty=true' -d '{
"query": {
 "bool": {
      "must": [
      {
            "match": { "body": "book" }
      },
      {
            "match": { "publised": "1" }
      }]
}}}'

My desired output if I search for the string book should match item #1 from the type items ("Hey there im reading a book") and item #2 from the type items_two ("Stephen kings book is very nice").

I don't want to change the mapping or anything else, I need to archieve this via one query, so how can I build my query?

Thanks in advance.

Upvotes: 0

Views: 61

Answers (1)

ChintanShah25
ChintanShah25

Reputation: 12672

You can use the _type field for these kind of searches. Try the following query

{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "match": {
                  "body": "text"
                }
              },
              {
                "match": {
                  "publised": "1"
                }
              }
            ],
            "filter": {
              "term": {
                "_type": "items_two"
              }
            }
          }
        },
        {
          "bool": {
            "must": [
              {
                "match": {
                  "body": "text"
                }
              }
            ],
            "filter": {
              "term": {
                "_type": "items"
              }
            }
          }
        }
      ]
    }
  }
}

Upvotes: 2

Related Questions