Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search by size of object type field elastic search

I have a mapping like this:

{
  "post": {
    "properties": {
      "author_gender": {
        "type": "string",
        "index": "not_analyzed",
        "omit_norms": true,
        "index_options": "docs"
      },
      "author_link": {
        "type": "string",
        "index": "no"
      },
      "content": {
        "type": "string"
      },
      "mentions": {
        "properties": {
          "id": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "profile_image_url": {
            "type": "string"
          },
          "screen_name": {
            "type": "string"
          }
        }
      }
   }
}

I need to search by the size of the mentions object. I have tried this:

{
  "filter": {
    "script": {
      "script": "doc['mentions'].values.length == 2"
    }
  }
}

This is not working. Gives an error

nested: ElasticSearchIllegalArgumentException[No field found for [mentions] in mapping with types [post]];

I have also tried replacing the script part with doc['mentions.id'].value.length == 2. It is also erroring

nested: ArrayIndexOutOfBoundsException[10];

How to query records with mentions object size 2 ?

like image 344
rubyprince Avatar asked Jun 26 '13 07:06

rubyprince


People also ask

What is size in Elasticsearch?

The size parameter is the maximum number of hits to return. Together, these two parameters define a page of results. Avoid using from and size to page too deeply or request too many results at once. Search requests usually span multiple shards.

What is type in Elasticsearch?

Basically, a type in Elasticsearch represented a class of similar documents and had a name such as customer or item . Lucene has no concept of document data types, so Elasticsearch would store the type name of each document in a metadata field of a document called _type.

How do you search data in Elasticsearch index?

You can use the search API to search and aggregate data stored in Elasticsearch data streams or indices. The API's query request body parameter accepts queries written in Query DSL. The following request searches my-index-000001 using a match query. This query matches documents with a user.id value of kimchy .


1 Answers

The elasticsearch guide recommends using size() instead of length for objects. So try this:

{
 "filter": {
   "script": {
     "script": "doc['mentions.id'].values.size() == 2"
    }
  }
}

All the best.

like image 78
Sai Avatar answered Oct 21 '22 06:10

Sai