如何在Spring Data Elasticsearch中使用多项过滤器?

ef1yzkbh  于 8个月前  发布在  ElasticSearch
关注(0)|答案(1)|浏览(59)

我希望实现以下rest API:

POST /t_source_item/_search?typed_keys=true&search_type=query_then_fetch
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "tags.id": {
              "value": "1"
            }
          }
        },
        {
          "term": {
            "tags.id": {
              "value": "2"
            }
          }
        }
      ]
    }
  }
}

下面是我写的代码:

import org.springframework.data.elasticsearch.client.elc.NativeQuery

val query = NativeQuery.builder().withQuery { q1 ->
    q1.bool { b ->
        b.filter { q2 ->
            q2.term { tq ->
                listOf(1L, 2L).forEach { t ->
                    tq.field("tags.id").value(t)
                }
                tq
            }
        }
    }
}.build()
val searchHits = elasticsearchOperations.search(query, Book::class.java)

但是我总是只得到最后一个term而不是多个term,其余的API结果如下:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "tags.id": {
              "value": 2
            }
          }
        }
      ]
    }
  }
}

正确的做法应该是什么?我用的是spring-data-elasticsearch:5.0.3

aor9mmx1

aor9mmx11#

您正在使用forEach和标签id来设置同一项查询的id,这就是为什么您只看到最后一个设置的值。必须使用循环创建单独的筛选查询:

val query = NativeQuery.builder().withQuery { q1 ->
  q1.bool { b ->
    listOf(1L, 2L).forEach { t ->
      b.filter { q2 ->
        q2.term { tq ->
          tq.field("tags.id").value(t)
          tq
        }
      }
    }
    b
  }
}.build()

使用范围而不是listOf的替代版本:

val query = NativeQuery.builder().withQuery { q1 ->
  q1.bool { b ->
    for (t in 1L..2L) {
      b.filter { q2 ->
        q2.term { tq ->
          tq.field("tags.id").value(t)
          tq
        }
      }
    }
    b
  }
}.build()

相关问题