Value conversion (transformation) in query

Is it possible to convert a string value to a float value in an advanced query in order to do basic math?

1 Like

Demonstration: Parsing Strings into Numbers in Logseq Queries

This example demonstrates how to parse string values into numbers using read-string in a Logseq advanced query. The query also shows how to handle invalid inputs gracefully and calculate a total sum from valid numeric values.

Query Code

#+BEGIN_QUERY
{
:title "Sum Parsed Numbers with Hard-Coded Data"
  :query [:find ?nonexistent
          :where [?b :block/properties ?props]
                 [(get ?props :zyx) ?nonexistent]
                 [(= ?nonexistent "000")]] ;; Query for a non-existent property

 :result-transform (fn [blip]
                    (let [hard-coded-data [{:raw-amount "3"}
                                           {:raw-amount "5"}
                                           {:raw-amount "invalid"}]
                          realized-rows (for [item hard-coded-data]
                                          (let [raw (:raw-amount item)
                                                parsed (read-string raw)]
                                            {:raw-amount raw
                                             :parsed-amount (if (number? parsed) parsed 0)}))
                          total (reduce + (for [row realized-rows] (:parsed-amount row)))]
                      {:data {:rows realized-rows :total total}}))

:view (fn [{:keys [data]}]
        [:div
         [:table {:class "table-auto"}
          [:thead
           [:tr
            [:th "Raw Amount"]
            [:th "Parsed Amount"]]]
          [:tbody
           (for [{:keys [raw-amount parsed-amount]} (:rows data)]
             [:tr
              [:td raw-amount]
              [:td (if (number? parsed-amount) parsed-amount "n/a")]])]]
         [:p [:strong "Total: "] (str (get data :total))]])
}
#+END_QUERY

Example Input Data

Page 1

amount-raw:: "5"

Page 2

amount-raw:: "3"

Page 3

amount-raw:: "invalid"

Expected Output

Table

Raw Amount Parsed Amount
3 3
5 5
invalid n/a

Total

Total: 8

How It Works

  1. Parsing with read-string:

    • The :result-transform step uses read-string to parse the :amount-raw value into a numeric type.
    • Non-numeric strings like "invalid" remain as strings and are filtered out.
  2. Handling Invalid Values:

    • Invalid values are shown as n/a in the table and excluded from the total sum.
  3. Dynamic Table Rendering:

    • The :view step renders a table showing both the raw string values and their parsed equivalents.
  4. Summing Numeric Values:

    • Only valid numeric values are summed to calculate the total.

This example provides a straightforward demonstration of string-to-number conversion and summing numeric data in Logseq queries. Let me know if you have any questions!

Can use [(* 1 ?str) ?float]