To do this, you could e.g. use a bool-query with a should
to weigh in a span_first-query which in turn has a span_multi
Here is a runnable example you can play with: https://www.found.no/play/gist/8107157
#!/bin/bash
export ELASTICSEARCH_ENDPOINT="http://localhost:9200"
# Index documents
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d '
{"index":{"_index":"play","_type":"type"}}
{"title":"Female"}
{"index":{"_index":"play","_type":"type"}}
{"title":"Female specimen"}
{"index":{"_index":"play","_type":"type"}}
{"title":"Microscopic examination of specimen from female"}
'
# Do searches
# This will match all documents.
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
"query": {
"prefix": {
"title": {
"prefix": "femal"
}
}
}
}
'
# This matches only the two first documents.
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
"query": {
"span_first": {
"end": 1,
"match": {
"span_multi": {
"match": {
"prefix": {
"title": {
"prefix": "femal"
}
}
}
}
}
}
}
}
'
# This matches all, but prefers the one's with a prefix match.
# It's sufficient that either of these match, but prefer that both matches.
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
"query": {
"bool": {
"should": [
{
"span_first": {
"end": 1,
"match": {
"span_multi": {
"match": {
"prefix": {
"title": {
"prefix": "femal"
}
}
}
}
}
}
},
{
"match": {
"title": {
"query": "femal"
}
}
}
]
}
}
}
'