在Elasticsearch中使用不同的映射搜索两种不同的类型

时间:2016-10-21 14:51:54

标签: elasticsearch

索引tester的以下映射有itemsitems_two两种类型:

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

我在上面放了三个元素。

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
}'

我需要创建一个与单词book匹配的查询,并且published = 1和映射上没有published的查询,但其上有book(作为items)的唯一项目。

使用以下查询,我只能与"Stephen kings book is very nice"项匹配(显然)。

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

如果我搜索字符串book,我想要的输出应该与类型items"Hey there im reading a book")和item#2中的项目#1匹配items_two 1}}("Stephen kings book is very nice")。

我不想更改映射或其他任何内容,我需要通过一个查询来解决这个问题,那么如何构建我的查询呢?

提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以使用_type字段进行此类搜索。请尝试以下查询

{
  "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"
              }
            }
          }
        }
      ]
    }
  }
}