Obsidian plug-in (1): Use of DataView

Use of DataView

1. Environment configuration

First, we need to install Obsidian . At the same time, the basic use of Obsidian will not be introduced here.

Dataview is a real-time indexing and query engine covering the OB knowledge base. You can associate data (such as tags, dates, snippets, numbers, etc.) with notes and then query (such as filter, sort, transform) the data. Using a form of database processing, by searching fields and filtering, and then displaying them in the form of lists and tables, it also supports advanced query forms of JavaScript.

Installation method:

Alternatively, we can also use GitHub to install. We download the file and unzip it <vault>/.obsidian/plugins/.

2. Introduction

1. Quick start

Official documentation: https://blacksmithgu.github.io/obsidian-dataview/

Dataview is an advanced query engine/index that generates dynamic views of the data in your knowledge base. You can generate views by using any value associated with the page, such as tag, folder, content, or field.

We can use ::to generate dataview data

Or, put this information on frontmatter, such as:

Then if we inquire,

```dataview
LIST "<br>**电影名**:" + Movie + "<br>**简介**:" + Brief + "<br>**评分**:" + Score + "<br>**年份**:" + Year + "<br>**类型**:" + Type + " " + Location 
FROM #entertain/movie 
WHERE contains(file.folder, "record_2023")
SORT Date desc
```

Then, we can generate a page like this:

2. Pages and fields

The core data abstraction of dataview is page , which refers to the markdwon page containing fields in your library . A field is an arbitrarily named piece of data - text, date, time period, link. These can be understood, displayed, and filtered by dataview. Fields can be defined in three ways:

  1. Frontmatter : All YAML frontmatter content will be automatically converted into dataview fields.

    ---
    tags: daily_node study/obsidian entertain/movie
    aliases: 
    describe: Obsidian 中 DataView 的使用
    Date: 2023-01-20
    Time: 09:26:28
    Author: Steve Anthony
    Email: [email protected]
    ---
    
  2. Inline field : A line <Name>:: <Value>of content formatted as will be automatically parsed as a field by dataview. Please note that you can use the <Name>standard Markdown format, but it will no longer be supported in the future.

    Movie:: [猎屠](https://v.qq.com/x/cover/mzc00200e7w52db/b0044upikcw.html)
    Brief:: 影片讲述某地发生电信诈骗事件,一名警员潜伏到中缅边境,深入电信诈骗中心,与诈骗犯罪集团斗智斗勇的故事,是一部反电信诈骗题材的院线片。
    Score:: 7.6
    Year:: 2022
    Type:: 犯罪 动作 剧情
    Location:: 内地
    
  3. Implicit fields (implicit) : dataview comes with a lot of metadata to annotate the page, such as the creation date of the file, any relevant dates, links in the file, tags, etc.

    If the file has a date within its title (in the format yyyy-mm-dd or yyyymmdd), or has a Date field/inline field, it also has the following attributes:

    • file.day: An implicit date for the file.

Field Type:

DataView supports several different field types:

  • Text : The global default is text. If a field does not match another specific type, it defaults to a plain text.
  • Number : Numbers are similar to '6' and '3.6'.
  • Boolean : true/false, just like the concept in programming.
  • Date : The universal date format defined by the ISO8601 standard YYYY-MM[-DDTHH:mm:ss]. The content after the month is optional.
  • Duration : The format of a duration is <time> <unit>, like 6 hoursor 4 minutes. Common English abbreviations such as 6hrsor are supported 2m.
  • Link : Ordinary Obsidian links such as [[Page]]or [[Page|Page Display]].
  • List: In YAML, lists composed of other dataview fields will be defined as ordinary YAML lists; for inline fields, they are just comma-separated lists.
  • Object : Mapping of name to dataview field. This can only be defined in the YAML title page using the common YANML object syntax. Object syntax:field: value1: 1 value2: 2 ...

The different field types are very important. This ensures that the dataview understands how to properly compare and sort values, and provides different operations.

3. Create query

Once you add useful data to relevant pages, you can display it or manipulate it somewhere. dataviewDataView creates inline queries through code blocks, writes the query code, and it will run dynamically and be displayed in the preview window of the note. There are three ways to write such a query:

  1. DataView's query language is a simplified, SQL-like language for quickly creating views. It supports basic arithmetic and comparison operations and is friendly to basic applications.
  2. The query language also provides inline queries, allowing you to embed a single value directly within a page - by = date(tody)creating today's date, or by = [[Page]].valueembedding a field on another page.
  3. The dataview JavaScript API provides you with the full functionality of JavaScript and provides a DSL for pulling Dataview data and executing queries, allowing you to create arbitrarily complex queries and views.

Query language functionality tends to lag compared to the JavaScript API, mainly because the JavaScript API is closer to the actual code; conversely, the query language is more stable and less likely to break during major updates to Dataview.

Calendars can also be created:

CALENDAR Date
FROM #daily_node
WHERE contains(file.folder, "record_2023")

4. System fields

  1. FROM

    FROMstatement determines which pages are initially collected and passed to other commands for further filtering. You can choose from any source , including folders, tags, internal links, and external links.

    • Tags : Select from tags (including sub-tags) to use FROM #tag.
    • Folders : Select from folders (including subfolders) to use FROM "folder".
    • Links : You can select a link to this file, or you can select a link to link this file to other pages:
    • [[note]]To get all pages linked to , use FROM [[note]].
    • To get all pages linked from [[note]](e.g., all links in a file), use FROM outgoing([[note]]).

    You can combine filters to get more advanced sources using "and" and "or".

    for example

    • #tag and "folder"All pages foldercontained in and will be returned .#tag
    • [[Food]] or [[Exercise]]Any links to [[Food]]or [[Exercise]]pages will be given.
  2. WHERE : Filter notes and aggregate conditions

  3. SORT : Sort according to what conditions

    You can give multiple fields to sort on. Sorting will be done on the basis of the first field. Then, if equality occurs, the second field is used to sort the equal fields. If there are still equality, the third field will be used for sorting, and so on.

    SORT field1 [ASCENDING/DESCENDING/ASC/DESC], ..., fieldN [ASC/DESC]
    
  4. GROUP BY:

    Group all results for a field. Each unique field value produces a row, which has two properties:

    • one corresponding to the field being grouped
    • One is rowsan array field containing all matching pages.
  5. LIMIT : Limit how many results are output

  6. FLATTEN : Split a result into multiple results based on a field or calculation.

    FLATTEN field
    FLATTEN (computed_field) AS name
    

3. Interface explanation

1. Expression

1.1 Overview

Dataview query language expressions can be any quantity that can produce a value. All fields are expressions. Literal values ​​such as eg 6, and calculated values field - 9​​​​are all expressions. Let’s make a more specific summary:

# 常规
field               (directly refer to a field)
simple-field        (refer to fields with spaces/punctuation in them like "Simple Field!")
a.b                 (if a is an object, retrieve field named 'b')
a[expr]             (if a is an object or array, retrieve field with name specified by expression 'expr')
f(a, b, ...)        (call a function called `f` on arguments a, b, ...)

# 算术运算
a + b               (addition)
a - b               (subtraction)
a * b               (multiplication)
a / b               (division)

# 比较运算
a > b               (check if a is greater than b)
a < b               (check if a is less than b)
a = b               (check if a equals b)
a != b              (check if a does not equal b)
a <= b              (check if a is less than or equal to b)
a >= b              (check if a is greater than or equal to b)

# 特殊操作
[[Link]].value      (fetch `value` from page `Link`)
1.2 Expression types

Comparison operators:

You can compare most numeric values ​​using various comparison operators. <, >, <=, >=, =, !=. This produces a boolean true or false value that can be used in a `WHERE' block in a query.

Object gets array:

array[<index>]You can index data from an array via the index operator , where <index>is any evaluated expression. Arrays are 0-indexed, so the first element is index 0, the second element is index 1, and so on. For example, list(1, 2, 3)[0] = 1.

You can also use the index operator to retrieve data from an object (which maps text to data values), in which case the index is a string/text rather than a number. You can also use shortcuts object.<name>where <name>is the index of the value. For example object("yes", 1).yes = 1.

function call

Dataview supports a variety of functions for manipulating data, which are fully described in the function documentation . Their general syntax is function(arg1, arg2, ...)- i.e. lower("yes")or regexmatch("text", ".+").

1.3 Certain types of interactions

Most dataview types have special interactions with operators or have additional fields that can be indexed using index operators.

date:

You can retrieve the different components of a date through indexes: date.year, date.month, date.day, date.hour. date.minute, date.second, date.week. You can also add a time period to the date to get a new date.

period:

Time periods can be added to each other or to dates. You can retrieve various components of a time period through indexes. duration.years, duration.months, duration.days, duration.hours, duration.minutes, duration.seconds.

Link:

You can "index" a link to get the value on the corresponding page. For example, [[Link]].valueyou will get the value from Linkthe page value.

2. Function

2.1 Constructor

Constructor creates value

object(key1, value1, ...)

Creates a new object with the given keys and values. Keys and values ​​should alternate within the call, and keys should always be strings/texts.

object() => empty object
object("a", 6) => object which maps "a" to 6
object("a", 4, "c", "yes") => object which maps a to 4, and c to "yes"

list(value1, value2, ...)

Creates a new list with the given values.

list() => empty list
list(1, 2, 3) => list with 1, 2, and 3
list("a", "b", "c") => list with "a", "b", and "c"

date(any)

Parses a date from the provided string, date or link object. If no result is found, null is returned.

date("2020-04-18") = <date object representing April 18th, 2020>
date([[2021-04-16]]) = <date object for the given page, refering to file.day>

number(string)

Extracts the first number from the given string and returns that number. If there are no numbers in the string, null is returned.

number("18 years") = 18
number(34) = 34
number("hmm") = null

link(path, [display])

Constructs a link object from the given file path or name. If there are two parameters, the second parameter is the display name of the link.

link("Hello") => link to page named 'Hello'
link("Hello", "Goodbye") => link to page named 'Hello', displays as 'Goodbye'

elink(url, [display])

Construct a link to an external URL (such as www.google.com). If there are two parameters, the second parameter is the display name of the link.

elink("www.google.com") => link element to google.com
elink("www.google.com", "Google") => link element to google.com, displays as "Google"
2.2 Commonly used functions

Numeric operations :

round(number, [digits])

Rounds a number to a specified number of digits. If the second argument is not specified, it is rounded to the nearest integer. Otherwise, round to the given number of digits.

round(16.555555) = 17
round(16.555555, 2) = 16.56

Object, array and string operations :

An operation that operates on the values ​​inside the container object.

contains(object|list|string, value)

Checks whether the given value exists in the given container type. This function behaves slightly differently based on whether the first argument is an object, a list, or a string.

  • For objects, checks whether the object has a key with the given name. like:contains(file, "ctime") = true contains(file, "day") = true (if file has a date in its title, false otherwise)
  • For lists, checks if any element in the array is equal to the given value. like:contains(list(1, 2, 3), 3) = true contains(list(), 1) = false
  • For strings, checks whether the given value is a substring of the string.contains("hello", "lo") = true contains("yes", "no") = false

extract(object, key1, key2, ...)

Extract multiple fields from an object and create a new object with the extracted fields.

extract(file, "ctime", "mtime") = object("ctime", file.ctime, "mtime", file.mtime)
extract(object("test", 1)) = object()

sort(list)

Sort the list and return a new sorted list.

sort(list(3, 2, 1)) = list(1, 2, 3)
sort(list("a", "b", "aa")) = list("a", "aa", "b")

reverse(list)

Reverse a list, returning a new reversed list.

reverse(list(1, 2, 3)) = list(3, 2, 1)
reverse(list("a", "b", "c")) = list("c", "b", "a")

length(object|array)

Returns the number of fields in an object, or the number of elements in an array.

length(list()) = 0
length(list(1, 2, 3)) = 3
length(object("hello", 1, "goodbye", 2)) = 2

sum(array)

Sum the numeric elements in an array.

sum(list(1, 2, 3)) = 6

all(array)

"true" will only be returned if all values ​​in the array are true. You can also pass multiple parameters to this function, and it will return `true' only if all parameters are true.

all(list(1, 2, 3)) = true
all(list(true, false)) = false
all(true, false) = false
all(true, true, true) = true

any(array)

Returns as long as any value in the array is true true. You can also pass multiple parameters to this function, and as long as any parameter is true, it will be returned true.

any(list(1, 2, 3)) = true
any(list(true, false)) = true
any(list(false, false, false)) = false
all(true, false) = true
all(false, false) = false

none(array)

If there are no elements in the array, return none.

join(array)

Concatenates the elements of an array into a string (i.e. renders all elements on the same line). If there is a second argument, then each element will be separated by the given delimiter.

join(list(1, 2, 3)) = "1, 2, 3"
join(list(1, 2, 3), " ") = "1 2 3"
join(6) = "6"
join(list()) = ""

String operations :

regexmatch(pattern, string)

Checks whether the given string matches the given pattern (using JavaScript regex engine).

regexmatch("\w+", "hello") = true
regexmatch(".", "a") = true
regexmatch("yes|no", "maybe") = false

regexreplace(string, pattern, replacement)

Replaces all instances of matching regex in "string" with "replacement" pattern. This uses JavaScript's replacement method, so you can use the special character such as $1to refer to the first capturing group, and so on.

regexreplace("yes", "[ys]", "a") = "aea"
regexreplace("Suite 1000", "\d+", "-") = "Suite -"

replace(string, pattern, replacement)

Replace all instances in replacementwith .stringpattern

replace("what", "wh", "h") = "hat"
replace("The big dog chased the big cat.", "big", "small") = "The small dog chased the small cat."
replace("test", "test", "no") = "no"

lower(string)

Converts all characters in a string to lowercase characters.

lower("Test") = "test"
lower("TEST") = "test"

upper(string)

Converts all characters in a string to uppercase characters.

upper("Test") = "TEST"
upper("test") = "TEST"
2.3 Tool functions

default(field, value)

If fieldempty, return value; otherwise return field. Useful for replacing null values ​​with default values. For example, to display projects that are not yet complete, use "incomplete"as their default value.

default(dateCompleted, "incomplete")

The default value is a vector in both arguments; if you need to explicitly use a default value in a list argument, use , ldefaultwhich is the same as default but is not vectorized.

default(list(1, 2, null), 3) = list(1, 2, 3)
ldefault(list(1, 2, null), 3) = list(1, 2, null)

choice(bool, left, right)

A primitive if statement – ​​if the first argument is true, the contents of the second argument are returned; otherwise, the contents of the third argument are returned.

choice(true, "yes", "no") = "yes"
choice(false, "yes", "no") = "no"
choice(x > 4, y, z) = y if x > 4, else z

striptime(date)

Strip the time part from the date, leaving only the year, month, and day. This is fine if you don't care about time when comparing dates.

striptime(file.ctime) = file.cday
striptime(file.mtime) = file.mday

おすすめ

転載: blog.csdn.net/qq_62789540/article/details/128742464