【问题标题】:How to return documents from elasticsearch, based on the first element of array of strings?如何根据字符串数组的第一个元素从弹性搜索返回文档?
【发布时间】:2019-06-25 15:36:35
【问题描述】:

我在弹性搜索中有如下​​文档:

[
     {
       _index: myindex,
       name: John,
       hobbies: Swimming, Golfing
     },
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing, Swimming
     },
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing
     },
]

我需要一种方法来返回所有Hobbies 在爱好字段中列为首位的文档。

我正在使用弹性搜索 NEST 库来解决这个问题。我创建了一个弹性搜索服务,用 C# 构建来创建我的查询。在此服务中,我查找所有用户并将过滤器应用于搜索。在这种情况下,我想首先获取所有Hobbies 列为Golfing 的文档,如果Golfing 不是第一个爱好,那么我不想要这些文档。

型号:

public class User {
  public const string Name {get; set;}
  public List<string> Hobbies {get; set;}
}

我的查询:

 query = query.Bool(b => b
    .Filter(filter => filter
      .Bool(b2 => b2
        .Must(must => must
          .Match(match => match
             .Field(l => l.Hobbies.First() == "Golfing")
            )
          )
       )

    )
);

我想过滤文档,以便我只获取爱好首先列为高尔夫的文档。我的预期结果应该是:

[
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing, Swimming
     },
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing
     },
]

但是,它会返回所有三个。我如何使它只返回文档,其爱好是打高尔夫球作为第一个爱好?

【问题讨论】:

    标签: c# .net elasticsearch nest


    【解决方案1】:

    我认为实现这一点的唯一方法是使用scrip query

    在你的情况下是这样的:

    var response = client.Search(s => s
       .Query(q => q
           .Script(sq => sq
                .Source("doc['hobbies'].value[0]. == 'Golfing'")
                )
           )
       )
    );
    

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 2021-09-27
      • 1970-01-01
      • 2023-03-09
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多