Aggregations on nested documents with painless scriptingElasticsearch, how to convert ip long to string, to get ip subnets aggsElastic nested multi_match exceptionElasticsearch : Is it possible to not analysed aggregation query on analysed field?Aggregate over last documents in elasticsearchElastic search by external id from other typeQuery on nested type with aggregation on nested types returns unexpected resultsElastic Search Painless Script Documentelasticsearch painless combination with key of aggregation and its nested aggregation keySort by multiple values based on nested document

Can you perfectly wrap a cube with this blocky shape?

What is the meaning of [[:space:]] in bash?

How to determine the optimal threshold to achieve the highest accuracy

Using two linked programs, output ordinal numbers up to n

Bone Decomposition

What is the word for "event executor"?

If SWIFT is headquartered in Europe, why does the EU need to create a SWIFT alternative to be able to do transactions with Iran?

Finding the package which provides a given command

Why does FFmpeg choose 10+20+20 ms instead of an even 16 ms for 60 fps GIF images?

When to ask for constructive criticism?

What exactly is a Hadouken?

Index Uniqueness Overhead

What made Windows ME so crash-prone?

Is it rude to refer to janitors as 'floor people'?

How to say no to more work as a PhD student so I can graduate

What advantages do focused Arrows of Slaying have over more generic ones?

Why did Steve Rogers choose this character in Endgame?

Intel 8080-based home computers

Can I remove the doors before installing a sliding patio doors frame?

Is there an English equivalent for "Les carottes sont cuites", while keeping the vegetable reference?

Adjusting vertical spacing in fractions?

Is the Gritty Realism variant incompatible with dungeon-based adventures?

Returning strings showing all vertices from all polygons in shapefile using ArcPy?

Alternator dying so junk car?



Aggregations on nested documents with painless scripting


Elasticsearch, how to convert ip long to string, to get ip subnets aggsElastic nested multi_match exceptionElasticsearch : Is it possible to not analysed aggregation query on analysed field?Aggregate over last documents in elasticsearchElastic search by external id from other typeQuery on nested type with aggregation on nested types returns unexpected resultsElastic Search Painless Script Documentelasticsearch painless combination with key of aggregation and its nested aggregation keySort by multiple values based on nested document






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















USING ELASTIC SEARCH 6.2
So I have a deeply nested document structure which has all the proper mapping (nested, text, keyword, etc). A sample document is as follows:




"type": "Certain Type",
"lineItems": [

"lineValue": 10,
"events": [

"name": "CREATED",
"timeStamp": "TIME VALUE"
,

"name": "ENDED",
"timeStamp": "TIME VALUE"

]

]



What I want to do is find out the average time required for all lines to go from CREATED to ENDED.



I created the following query



GET /_search

"size": 0,
"query":
"match":
"type": "Certain Type"

,
"aggs":
"avg time":
"nested":
"path": "lineItems.events"
,
"aggs":
"avg time":
"avg":
"script":
"lang": "painless",
"source": """
long timeDiff = 0;
long fromTime = 0;
long toTime = 0;
if(doc['lineItems.events.name.keyword'] == "CREATED")
fromTime = doc['lineItems.events.timeValue'].value.getMillis();

else if(doc['lineItems.events.name.keyword'] == "ENDED")
toTime = doc['lineItems.events.timeValue'].value.getMillis();

timeDiff = toTime-fromTime;
return (timeDiff)
"""









The Result was that I got 0 as the aggregation result which is wrong.



Is there any way to achieve this?










share|improve this question




























    1















    USING ELASTIC SEARCH 6.2
    So I have a deeply nested document structure which has all the proper mapping (nested, text, keyword, etc). A sample document is as follows:




    "type": "Certain Type",
    "lineItems": [

    "lineValue": 10,
    "events": [

    "name": "CREATED",
    "timeStamp": "TIME VALUE"
    ,

    "name": "ENDED",
    "timeStamp": "TIME VALUE"

    ]

    ]



    What I want to do is find out the average time required for all lines to go from CREATED to ENDED.



    I created the following query



    GET /_search

    "size": 0,
    "query":
    "match":
    "type": "Certain Type"

    ,
    "aggs":
    "avg time":
    "nested":
    "path": "lineItems.events"
    ,
    "aggs":
    "avg time":
    "avg":
    "script":
    "lang": "painless",
    "source": """
    long timeDiff = 0;
    long fromTime = 0;
    long toTime = 0;
    if(doc['lineItems.events.name.keyword'] == "CREATED")
    fromTime = doc['lineItems.events.timeValue'].value.getMillis();

    else if(doc['lineItems.events.name.keyword'] == "ENDED")
    toTime = doc['lineItems.events.timeValue'].value.getMillis();

    timeDiff = toTime-fromTime;
    return (timeDiff)
    """









    The Result was that I got 0 as the aggregation result which is wrong.



    Is there any way to achieve this?










    share|improve this question
























      1












      1








      1


      1






      USING ELASTIC SEARCH 6.2
      So I have a deeply nested document structure which has all the proper mapping (nested, text, keyword, etc). A sample document is as follows:




      "type": "Certain Type",
      "lineItems": [

      "lineValue": 10,
      "events": [

      "name": "CREATED",
      "timeStamp": "TIME VALUE"
      ,

      "name": "ENDED",
      "timeStamp": "TIME VALUE"

      ]

      ]



      What I want to do is find out the average time required for all lines to go from CREATED to ENDED.



      I created the following query



      GET /_search

      "size": 0,
      "query":
      "match":
      "type": "Certain Type"

      ,
      "aggs":
      "avg time":
      "nested":
      "path": "lineItems.events"
      ,
      "aggs":
      "avg time":
      "avg":
      "script":
      "lang": "painless",
      "source": """
      long timeDiff = 0;
      long fromTime = 0;
      long toTime = 0;
      if(doc['lineItems.events.name.keyword'] == "CREATED")
      fromTime = doc['lineItems.events.timeValue'].value.getMillis();

      else if(doc['lineItems.events.name.keyword'] == "ENDED")
      toTime = doc['lineItems.events.timeValue'].value.getMillis();

      timeDiff = toTime-fromTime;
      return (timeDiff)
      """









      The Result was that I got 0 as the aggregation result which is wrong.



      Is there any way to achieve this?










      share|improve this question














      USING ELASTIC SEARCH 6.2
      So I have a deeply nested document structure which has all the proper mapping (nested, text, keyword, etc). A sample document is as follows:




      "type": "Certain Type",
      "lineItems": [

      "lineValue": 10,
      "events": [

      "name": "CREATED",
      "timeStamp": "TIME VALUE"
      ,

      "name": "ENDED",
      "timeStamp": "TIME VALUE"

      ]

      ]



      What I want to do is find out the average time required for all lines to go from CREATED to ENDED.



      I created the following query



      GET /_search

      "size": 0,
      "query":
      "match":
      "type": "Certain Type"

      ,
      "aggs":
      "avg time":
      "nested":
      "path": "lineItems.events"
      ,
      "aggs":
      "avg time":
      "avg":
      "script":
      "lang": "painless",
      "source": """
      long timeDiff = 0;
      long fromTime = 0;
      long toTime = 0;
      if(doc['lineItems.events.name.keyword'] == "CREATED")
      fromTime = doc['lineItems.events.timeValue'].value.getMillis();

      else if(doc['lineItems.events.name.keyword'] == "ENDED")
      toTime = doc['lineItems.events.timeValue'].value.getMillis();

      timeDiff = toTime-fromTime;
      return (timeDiff)
      """









      The Result was that I got 0 as the aggregation result which is wrong.



      Is there any way to achieve this?







      elasticsearch elasticsearch-painless






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 8:20









      Anirudh KanabarAnirudh Kanabar

      234 bronze badges




      234 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Use doc[ in nested object script does not work as nested are a new document for elastic search.



          Use params._source instead (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html). Note access to source would be really slow, if you have a lot of documents or if you need to request this query a lot, consider add this field on main document.



          I consider all value exist, add if robustness test if needed, this should work.



          long toTime = 0; 
          long fromTime = 0;
          timeDiff = params['_source']['ENDED']
          fromTime = params['_source']['CREATED']
          return (toTime - fromTime);





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55352602%2faggregations-on-nested-documents-with-painless-scripting%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Use doc[ in nested object script does not work as nested are a new document for elastic search.



            Use params._source instead (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html). Note access to source would be really slow, if you have a lot of documents or if you need to request this query a lot, consider add this field on main document.



            I consider all value exist, add if robustness test if needed, this should work.



            long toTime = 0; 
            long fromTime = 0;
            timeDiff = params['_source']['ENDED']
            fromTime = params['_source']['CREATED']
            return (toTime - fromTime);





            share|improve this answer





























              0














              Use doc[ in nested object script does not work as nested are a new document for elastic search.



              Use params._source instead (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html). Note access to source would be really slow, if you have a lot of documents or if you need to request this query a lot, consider add this field on main document.



              I consider all value exist, add if robustness test if needed, this should work.



              long toTime = 0; 
              long fromTime = 0;
              timeDiff = params['_source']['ENDED']
              fromTime = params['_source']['CREATED']
              return (toTime - fromTime);





              share|improve this answer



























                0












                0








                0







                Use doc[ in nested object script does not work as nested are a new document for elastic search.



                Use params._source instead (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html). Note access to source would be really slow, if you have a lot of documents or if you need to request this query a lot, consider add this field on main document.



                I consider all value exist, add if robustness test if needed, this should work.



                long toTime = 0; 
                long fromTime = 0;
                timeDiff = params['_source']['ENDED']
                fromTime = params['_source']['CREATED']
                return (toTime - fromTime);





                share|improve this answer















                Use doc[ in nested object script does not work as nested are a new document for elastic search.



                Use params._source instead (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html). Note access to source would be really slow, if you have a lot of documents or if you need to request this query a lot, consider add this field on main document.



                I consider all value exist, add if robustness test if needed, this should work.



                long toTime = 0; 
                long fromTime = 0;
                timeDiff = params['_source']['ENDED']
                fromTime = params['_source']['CREATED']
                return (toTime - fromTime);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 26 at 17:48









                marc_s

                597k135 gold badges1147 silver badges1284 bronze badges




                597k135 gold badges1147 silver badges1284 bronze badges










                answered Mar 26 at 9:26









                LeBigCatLeBigCat

                6764 silver badges12 bronze badges




                6764 silver badges12 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55352602%2faggregations-on-nested-documents-with-painless-scripting%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                    Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?