I have an index for an example airport:
public class FlightIndex
{
public int Id { get; set; }
[keyword]
public string Destination { get; set; }
}
The Destination
field stores data like "London Airport," :London Airport (XYZ)," and "London Airport (ABC)."
I would like to search and return the exact match on Destination
.
In the query below, I want a list of flights whose destination matches the destination list provided:
q.Terms(m => m.Field(f => f.Destination).Terms(parameters.Destinations
.Select(_ => _.ToLower()).ToList()));
For example, if parameters.Destinations
contains "London Airport (ABC)," then nothing is returned, but if it has "London Airport," it returns the ones with "London Airport."
It does not seem to work with the brackets.
I'm not sure if it needs/can to be escaped.
It sounds very much like Destination
is not indexed as a keyword
datatype; if it was, a terms
query would return matches for verbatim input values. Additionally, parentheses would not make a difference, the indexed value would either match exactly or not.
I would check the mapping in the target index with the Get Mapping API.
Here's an example to demonstrate it working
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)")
)
)
);
sends the following requests and receives responses
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)"
}
}
]
}
}
------------------------------