简体   繁体   中英

Return first n element from array in elasticsearch query

I have an array field in document named as IP which contains above 10000 ips as element.

for eg

IP:["192.168.a:A","192.168.a:B","192.168.a:C","192.168.A:b"...........]

Now i made a search query with some filter and i got the results but the problem is size of result very huge because of above field.

Now I want to fetch only N ips from array let say only 10 order doesn't matters.

So How do i do that...

update:

Apart from IP field there are others fields also and i applied filter on that field not on IP .I want whole document which satisfies filters .I just want to limit the number of elements in single IP fields.(Let me know if there is any other way apart from using script also ).

This kind of request could solve your problem :

GET ips/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "truncate_ip": {
      "script": {
        "source": """
        String[] trunc_ip = new String[10];
        for (int i = 0; i < 10; ++i) {
              trunc_ip[i]= params['_source']['IP'][i];
            }
          return trunc_ip;
        """
      }
    }
  
  }
}

By default ES returns only 10 matching results so I am not sure what is your search query and what exactly you want to restrict

  1. no of elements in single ip field
  2. No of ip fields matching your search results

Please clarify above and provide your search query to help further.

You can use scriptedFields for generating a new field from existing fields in Elastic Search. Details added as comments.

GET indexName/_search
{
  "_source": {
    "excludes": "ips"  //<======= Exclude from source the IP field (change the name based on your document)
  }, 
  "query": {
    "match_all": {} // <========== Define relevant filters
  },
  "script_fields": {
    "limited_ips": { // <========= add a new scipted field
      "script": { 
        "source": "params['_source'].ips.stream().limit(2).collect(Collectors.toList())" // <==== Replace 2 with the number of i.ps you want in result.
      }
    }
  }
}

Note:

  1. If you remove _source then only the scripted field will be the part of the result.
  2. Apart from accessing the value of the field, the rest of the syntax is Java. Change as it suits you.
  3. Apart from non-analyzed text fields, use doc['fieldName'] to access the field with-in script. It is faster. See the below excerpt from ES docs :

By far the fastest most efficient way to access a field value from a script is to use the doc['field_name'] syntax, which retrieves the field value from doc values. Doc values are a columnar field value store, enabled by default on all fields except for analyzed text fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM