Elastic Nest Query返回与条款完全匹配

时间:2018-09-07 22:15:42

标签: elasticsearch arraylist nest

我有一个示例机场的索引:

public class FlightIndex
{
    public int Id { get; set; }
    [keyword]
    public string Destination { get; set; }
}

Destination字段存储“伦敦机场”,“伦敦机场(XYZ)”和“伦敦机场(ABC)”之类的数据。

我想搜索并返回Destination上的完全匹配项。

在下面的查询中,我想要一个列表,其目的地与提供的目的地列表相匹配:

q.Terms(m => m.Field(f => f.Destination).Terms(parameters.Destinations
.Select(_ => _.ToLower()).ToList()));

例如,如果parameters.Destinations包含“伦敦机场(ABC)”,则不返回任何内容,但如果包含“伦敦机场”,则返回包含“伦敦机场”的内容。

它似乎不适用于括号。

我不确定它是否需要/可以逃脱。

1 个答案:

答案 0 :(得分:0)

听起来很像Destination没有被索引为keyword数据类型;如果是,则terms查询将返回逐字输入值的匹配项。此外,括号不会产生任何影响,索引值将完全匹配或不匹配。

我将使用Get Mapping API检查目标索引中的映射。

这是一个演示其工作原理的例子

var client = new ElasticClient(settings);

if (client.IndexExists("example").Exists)
{
    client.DeleteIndex("example");
}

client.CreateIndex("example", c => c
    .Mappings(m => m
        .Map<FlightIndex>(mm => mm
            .AutoMap()
        )
    )
);

client.Index(new FlightIndex { Id = 1, Destination = "London Airport (XYZ)" }, i => i
    .Index("example")
    .Refresh(Refresh.WaitFor)
);

client.Search<FlightIndex>(s => s
    .Index("example")
    .Query(q => q
        .Terms(t => t
            .Field(f => f.Destination)
            .Terms("London Airport (XYZ)")
        )
    )
);

发送以下请求并接收响应

HEAD http://localhost:9200/example?pretty=true

Status: 200

------------------------------

PUT http://localhost:9200/example?pretty=true 
{
  "mappings": {
    "flightindex": {
      "properties": {
        "id": {
          "type": "integer"
        },
        "destination": {
          "type": "keyword"
        }
      }
    }
  }
}

Status: 200

{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "example"
}

------------------------------

PUT http://localhost:9200/example/flightindex/1?pretty=true&refresh=wait_for 
{
  "id": 1,
  "destination": "London Airport (XYZ)"
}

Status: 201

{
  "_index" : "example",
  "_type" : "flightindex",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

------------------------------

POST http://localhost:9200/example/flightindex/_search?pretty=true&typed_keys=true 
{
  "query": {
    "terms": {
      "destination": [
        "London Airport (XYZ)"
      ]
    }
  }
}

Status: 200

{
  "took" : 13,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "example",
        "_type" : "flightindex",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "id" : 1,
          "destination" : "London Airport (XYZ)"
        }
      }
    ]
  }
}

------------------------------
相关问题