Saturday, July 18, 2020

MARKLOGIC: Print the month & year from the specific date range in the YYYY_MM Fomat using XQUERY

Hi All,

Recently I got a request to print the labels(STRING) from the provided date range. The use case of this request is to create the collection based on the date. For example, if customer1 bought the product on 01-JAN-2020 & customer 2 bought the product on 01-FEB-2020 then we need to store the customer purchase details in the corresponding collection. The above data will be store as mentioned below.

2020_JAN(collection-URI) - /customer1.json
2020_FEB(collection-URI) - /customer2.json

suppose there is one more customer bought the product on 02-FEB-2020 then FEB-2020 collection has 2 customers details.

2020_JAN(collection-URI) -
     /customer1.json
2020_FEB(collection-URI) -
    /customer2.json
    /customer3.json

Below code is useful to implement the above feature in your code. I request you please provide your comments if there is any changes required.

(:

This query is useful to print the label from the specified date range.
These labels are very useful to bucketing the data using a date range

@Developer - Srinivasan
@updateDate - 18-Jul-2020
@version - 1.0
:)

(: input - provide start & end date in date format YYYY-MM-DD :)
let $startDate := xs:date("2010-06-01")
let $endDate := xs:date("2010-07-30")

(: find the differences between date and used the same  :)
let $year-diff := year-from-date($endDate) - year-from-date($startDate)
let $month-diff := month-from-date($endDate) - month-from-date($startDate)

(: create map to store the intermedaite values :)
let $map := map:map()
let $_ := map:put($map,"date",$startDate)

(: prepare the label value in the format - YYYY_MM :)
let $printLabel :=
    for $each at $pos in (1 to (($year-diff * 12) + $month-diff) + 1)
    let $newDate := if($pos eq 1) then map:get($map,"date") else map:get($map,"date") + xs:yearMonthDuration("P1M")
    let $_ := map:put($map,"date",$newDate)
    where $newDate le $endDate
    return
        fn:format-date($newDate,"[Y0001]_[M01]")

(: return the prepared label format :)
return
    $printLabel

No comments:

Post a Comment