如何通过Nest api应用精确匹配?

时间:2014-11-05 00:38:48

标签: elasticsearch nest

如何AEntity BEntityProp等于“Bprop 3”?

internal class Program
{
    public class AEntity
    {
        public Guid Id { get; set; }
        public BEntity BEntityProp { get; set; }
    }

    public class BEntity
    {
        public Guid Id { get; set; }
        public string Bprop { get; set; }
    }

    private static void Main(string[] args)
    {
        var node = new Uri("http://localhost:9200");
        var settings = new ConnectionSettings(node, defaultIndex: "default_index");
        var client = new ElasticClient(settings);

        var entities = new List<AEntity>(100);

        for (var i = 0; i < 100; i++)
            client.Index(new AEntity
                {
                    Id = Guid.NewGuid(),
                    BEntityProp =
                        new BEntity
                        {
                            Id = Guid.NewGuid(),
                            Bprop = "Bprop " + i.ToString(CultureInfo.InvariantCulture)
                        }
                });

        Thread.Sleep(1000);

        var searchDescriptor = new SearchDescriptor<AEntity>();

        //how to apply exact instead match by Nest api?
        List<AEntity> expected = client.Search<AEntity>(
            searchDescriptor.Query(qd => qd.Match(
                mqd => mqd.OnField(x => x.BEntityProp.Bprop).Query("bprop 3")))).Documents.ToList();

        try
        {
            Assert.IsTrue(expected.Count == 1);
        }
        finally 
        {
            client.DeleteIndex(di => di.Indices("default_index", "default_index" + "*"));
        }
    }
}

结果我想要1个AEntity,Bprop等于“Bprop 3”,但我的所有匹配都是“Bprop”。

请求如下: 预期:

{
  "query": {
    "match": { <-- how to apply exact instead match by Nest api?
      "bEntityProp.bprop": {
        "query": "bprop 3"
      }
    }
  }
}

2 个答案:

答案 0 :(得分:1)

我找到了回答:

 List<AEntity> expected = client.Search<AEntity>(
            searchDescriptor.Query(qd => qd.MatchPhrase(
                mqd => mqd.OnField(x => x.BEntityProp.Bprop).Query("bprop 3")))).Documents.ToList();

答案 1 :(得分:0)

如果您想要完全匹配,请使用Term查询:

List<AEntity> expected = client.Search<AEntity>(
            searchDescriptor.Query(qd => qd.Term(
                mqd => mqd.OnField(x => x.BEntityProp.Bprop).Value("bprop 3"))))
                   .Documents.ToList();

有关术语与匹配的更多信息,请参阅此discussion