Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

elastic stack - Range results by position in array with ElasticSearch

I have some documents, indexed with Elasticsearch.

{ "name": "Item 1", "tags": [2,1,3] }
{ "name": "Item 2", "tags": [1,2,3] }
{ "name": "Item 3", "tags": [2,3,4] }

How can I make a query to filter these items by having tag 1 (integer) and moreover, range them by its position in tags array?

query: 1 => Item 2, Item 1
query: 2 => Item 1, Item 3, Item 2
question from:https://stackoverflow.com/questions/66049481/range-results-by-position-in-array-with-elasticsearch

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use a scripted sort as follows:

POST index_name/_search
{
  "query": {
    "term": {
      "tags": {
        "value": 1
      }
    }
  },
  "sort": [
    {
      "_script": {
        "type": "number",
        "script": {
          "lang": "painless",
          "source": "params._source.tags.indexOf(params.target)",
          "params": {
            "target": 1
          }
        },
        "order": "asc"
      }
    }
  ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...