옵시디언 활용/Dataview

Dataview 기초: 함수

반응형

개요

Dataview는 다양한 내장 함수를 제공하여 사용자가 데이터를 더 유연하게 처리할 수 있습니다. 이번 시간엔 Dataview에서 자주쓰는 함수들을 알아보겠습니다.

구성 함수

날짜 date(any)

date("2023-12-22")
date("today")
date(["yesterday", "today", "tomorrow"])

지정한 날짜로 날짜 객체를 생성합니다.

기간 dur(any)

date(today) - dur(1 days)
date(today) - dur(1 week)
date(today) + dur(1 month)
date(today) + dur(1 year)

오늘로부터 1일 전, 일주일 전, 1달 후, 1년 후 등의 날짜를 계산할 수 있습니다.

숫자 number(string)

number("23년 전 우리는")

문자열에서 숫자만을 추출해낼 수 있습니다.

문자열 string(any)

string(18) = "18"
string(dur(8 hours)) = "8 hours"
string(date(2021-08-15)) = "August 15th, 2021"

숫자나 다른 데이터 타입을 문자열로 변환합니다.

내부 링크 link(path, 'display')

link("Note Path","Note Name")
link("Note Path")

내부링크를 연결할 때 link를 사용합니다 Note Path라는 노트 링크를 Note Name이라는 이름으로 출력합니다. 위키링크의 [[Note Path|Note Name]]와 비슷합니다.

외부 링크 elink(url, 'display')

elink("www.google.com","google")
elink("www.google.com")

외부링크입니다. 내부링크와 사용 방법은 같습니다.

임베드 생성 embed(link)

embed(link(A.png))

문서나 미디어를 임베드 해줍니다.

타입확인 typeof(any)

typeof(8) => "number"
typeof("text") => "string"
typeof([1, 2, 3]) => "array"
typeof({ a: 1, b: 2 }) => "object"
typeof(date(2020-01-01)) => "date"
typeof(dur(8 minutes)) => "duration"

숫자 연산 함수

반올림 round(number, 'digits')

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

소수점 이하 숫자를 반올림합니다. Digits의 숫자에 따라 소수점 이하 N개 자리수까지 표시되고 반올림합니다. Digits를 생략할 경우 소숫점만 반올림해줍니다.

합 연산 sum(array)

sum([1, 2, 3]) = 6
sum(list(1,2,3,4,5)) = 15

곱 연산 product(array)

product([1,2,3]) = 6
product(list(1,2,3,4,5)) = 120

평균 average(array)

average([1, 2, 3]) = 2

문자열 연산

regextest(pattern, string)

주어진 정규 표현식 패턴이 문자열 내에서 발견되는지 확인합니다(JavaScript 정규 표현식 엔진을 사용).

regextest("\w+", "hello") = true
regextest(".", "a") = true
regextest("yes|no", "maybe") = false
regextest("what", "what's up dog?") = true

regexmatch(pattern, string)

주어진 정규 표현식 패턴이 전체 문자열과 일치하는지 확인합니다. 이것은 regextest와 달리 텍스트의 일부분만 일치해도 됩니다.

regexmatch("\w+", "hello") = true
regexmatch(".", "a") = true
regexmatch("yes|no", "maybe") = false
regexmatch("what", "what's up dog?") = false

regexreplace(string, pattern, replacement)

문자열 내에서 정규 표현식 패턴과 일치하는 모든 인스턴스를 대체로 교체합니다. 이것은 JavaScript의 replace 메소드를 내부적으로 사용하므로, $1과 같은 특수 문자를 사용하여 첫 번째 캡처 그룹을 참조할 수 있습니다.

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

replace(string, pattern, replacement)

문자열 내에서 패턴의 모든 인스턴스를 대체로 교체합니다.

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)

문자열을 모두 소문자로 변환합니다.

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

upper(string)

문자열을 모두 대문자로 변환합니다.

upper("Test") = "TEST"
upper("test") = "TEST"

split(string, delimiter, [limit])

주어진 구분자 문자열에 따라 문자열을 분할합니다. 세 번째 인수가 제공되면 발생하는 분할의 수를 제한합니다. 구분자 문자열은 정규 표현식으로 해석됩니다. 구분자에 캡처 그룹이 있으면, 일치하는 것들이 결과 배열에 삽입되고, 일치하지 않는 캡처는 빈 문자열입니다.

split("hello world", " ") = list("hello", "world")
split("hello  world", "\s") = list("hello", "world")
split("hello there world", " ", 2) = list("hello", "there")
split("hello there world", "(t?here)") = list("hello ", "there", " world")
split("hello there world", "( )(x)?") = list("hello", " ", "", "there", " ", "", "world")

startswith(string, prefix)

문자열이 주어진 접두사로 시작하는지 확인합니다.

startswith("yes", "ye") = true
startswith("path/to/something", "path/") = true
startswith("yes", "no") = false

endswith(string, suffix)

문자열이 주어진 접미사로 끝나는지 확인합니다.

endswith("yes", "es") = true
endswith("path/to/something", "something") = true
endswith("yes", "ye") = false

padleft(string, length, [padding])

원하는 길이에 도달할 때까지 문자열 왼쪽에 패딩을 추가하여 문자열을 채웁니다. 패딩 문자를 생략하면 기본적으로 공백이 사용됩니다.

padleft("hello", 7) = "  hello"
padleft("yes", 5, "!") = "!!yes"

padright(string, length, [padding])

padleft와 동등하지만, 오른쪽에 패딩을 추가합니다.

padright("hello", 7) = "hello  "
padright("yes", 5, "!") = "yes!!"

substring(string, start, [end])

시작에서 끝까지(또는 지정하지 않은 경우 문자열의 끝까지) 문자열의 일부를 추출합니다.

substring("hello", 0, 2) = "he"
substring("hello", 2, 4) = "ll"
substring("hello", 2) = "llo"
substring("hello", 0) = "hello"

truncate(string, length, [suffix])

접미사를 포함하여 주어진 길이 이하가 되도록 문자열을 잘라냅니다. 일반적으로 테이블에서 긴 텍스트를 자를 때 유용합니다.

truncate("Hello there!", 8) = "Hello..."
truncate("Hello there!", 8, "/") = "Hello t/"
truncate("Hello there!", 10) = "Hello t..."
truncate("Hello there!", 10, "!") = "Hello the!"
truncate("Hello there!", 20) = "Hello there!"

유틸 함수

기본값 default(field, value)

default(field, value) 함수는 속성에 기본값을 추가하는 기능을 합니다. 즉, 속성값이 비어있으면 기본값 value를 반환하고, 그렇지 않으면 속성값을 반환합니다.

default(page.important, "보통")

노트에 page.important라는 프론트메터가 없거나, 있어도 값이 없을 경우, 기본값 보통을 출력합니다.

속성에 값이 있는지 유무만 판단하면 되는 경우가 있습니다. 특정 속성이 비어있지 않지만 속성값이 리스트 타입이고, 비어있는 값이 있는 경우, default()를 사용하면 리스트 내의 모든 비어있는 값을 대체하게 됩니다. 이런 경우에는 ldefault() 함수를 사용해야 합니다.

default(list(1, 2, null), 3)    // 결과는 [1, 2, 3]
ldefault(list(1, 2, null), 3)   // 결과는 [1, 2, null]

ldefault를 사용하면 리스트 내부의 비어있는 값을 대체하지 않습니다.

시간제거 striptime(date)

striptime(date)함수는 날짜에서 시간 부분을 제거하고 연, 월, 일만 남깁니다.

striptime(file.ctime) 

결과값은 file.cday

striptime(file.mtime)

결과값은 file.mday

striptime(date(2024-01-01T12:00)) 

12:00은 제거하고 2024년 1월 1일을 출력합니다.

조건 choice(bool, left, right)

choice(bool, left, right) 함수는 첫 번째 인자가 참이면 왼쪽 값을, 그렇지 않으면 오른쪽 값을 반환합니다.

choice(page.status = "Done", "완료", "미완료")

page.status의 값이 Done일 경우, 완료로 출력. 아닐경우 미완료로 출력합니다.

choice(date(today) > date(page.duedate), "마감 기한 초과", "마감 기한 내")

오늘 날짜가 page.duedate보다 뒤에 있으면 마감 기한 초과를, 그렇지 않으면 마감 기한 내를 출력합니다.

날짜포맷 dateformat(date|datetime, string)

dateformat(date|datetime, string)함수는 날짜를 문자열로 형식화합니다. 날짜형식은 Luxon date format Option을 따릅니다.

dateformat(date(today),"yyyy년 M월 d일")
dateformat(date(today),"yyyy-MM-dd")

2024년 2월 1일과 같이 오늘 날짜를 원하는 형식으로 출력할 수 있습니다.

기간포맷 durationformat(duration, string)

durationformat(duration, string)함수는 정해진 시간을 문자열로 형식화 합니다.

자리 표시자 단위
S 밀리초
s
m
h 시간
d
w
M
y
durationformat(dur("12 days 3 hours 45 seconds"), "ddd'일' hh'시간' ss'초'")

ddd, hh, ss는 개수에 따라 자리수를 나타냅니다. 결과값은 "012일 03시간 45초"로 출력됩니다.

durationformat(dur("123 days 4 hours 56 minutes"), "yyyy ddd hh mm ss") 

결과값은 "0123 000 04 56 00"으로 출력됩니다.

durationformat(dur("2000 years"), "M 달")

결과값은 "24000 달"로 출력됩니다.

durationformat(dur("14d"), "s '초'")

결과값은 "1209600 초"입니다.

localtime(date)

localtime(date)함수는 고정 시간대의 날짜를 현재 시간대의 날짜로 변환합니다.

localtime(date(now))

meta(link)

meta(link)는 링크에 포함된 5가지 메타데이터를 구성하는 객체를 가져옵니다.

링크는 다음으로 구성되어있습니다.

![[링크(#헤더)(^블록ID)|표시 이름]]
  • meta(link).display: 표시 이름을 출력합니다. 없으면 빈 문자열로 출력됩니다.
  • meta(link).embed: 임베드 여부를 확인합니다. !가 있으면 true, 없으면 false.
  • meta(link).path: 링크의 경로를 출력합니다.
  • meta(link).subpath: 링크의 하위 경로(헤더나 블록ID)를 출력합니다. 없으면 빈 문자열로 출력됩니다.
  • meta(link).type: 링크 타입을 출력합니다. 파일만 링크된 경우 file, 파일의 헤더에 링크된 경우 header, 블록ID에 링크된 경우 block을 출력합니다.

객체, 배열, 문자열 연산

컨테이너 객체 안의 값을 조작하는 연산들입니다.

contains(object|list|string, value)

주어진 컨테이너 타입이 주어진 값을 포함하는지 확인합니다. 이 함수는 첫 번째 인자가 객체, 리스트, 또는 문자열인지에 따라 약간 다르게 동작합니다. 이 함수는 대소문자를 구분합니다.

  • 객체의 경우, 객체가 주어진 이름의 키를 가지고 있는지 확인합니다. 예를 들어,
contains(file, "ctime") = true  
contains(file, "day") = true\` (파일 제목에 날짜가 있으면 true, 그렇지 않으면 false)  
  • 리스트의 경우, 배열 요소 중 어느 하나라도 주어진 값을 가지고 있는지 확인합니다. 예를 들어,
contains(list(1, 2, 3), 3) = true  
contains(list(), 1) = false  
  • 문자열의 경우, 주어진 값이 문자열 내에 부분 문자열(즉, 내부에 위치)인지 확인합니다.
contains("hello", "lo") = true  
contains("yes", "no") = false  

icontains(object|list|string, value)

contains()의 대소문자를 구분하지 않는 버전입니다.

econtains(object|list|string, value)

econtains은 문자열/리스트 내에서 정확한 일치를 찾는지 확인합니다. 이 함수는 대소문자를 구분합니다.

  • 문자열의 경우, contains()와 정확히 같은 방식으로 동작합니다.
econtains("Hello", "Lo") = false  
econtains("Hello", "lo") = true  
  • 리스트의 경우, 리스트 내에 정확한 단어가 있는지 확인합니다.
econtains(["These", "are", "words"], "word") = false  
econtains(["These", "are", "words"], "words") = true  
  • 객체의 경우, 정확한 키 이름이 객체 내에 있는지 확인합니다. 재귀적 검사는 수행하지 않습니다.
econtains({key:"value", pairs:"here"}, "here") = false  
econtains({key:"value", pairs:"here"}, "key") = true  
econtains({key:"value", recur:{recurkey: "val"}}, "value") = false  
econtains({key:"value", recur:{recurkey: "val"}}, "Recur") = false  
econtains({key:"value", recur:{recurkey: "val"}}, "recurkey") = false  

containsword(list|string, value)

값이 문자열 또는 리스트에 정확한 단어로 일치하는지 확인합니다. 대소문자를 구분하지 않습니다. 입력 유형에 따라 출력이 다릅니다.

  • 문자열의 경우, 주어진 문자열 내에 단어가 있는지 확인합니다.
containsword("word", "word") = true  
containsword("word", "Word") = true  
containsword("words", "Word") = false  
containsword("Hello there!", "hello") = true  
containsword("Hello there!", "HeLLo") = true  
containsword("Hello there chaps!", "chap") = false  
containsword("Hello there chaps!", "chaps") = true  
  • 리스트의 경우, 단어의 정확한 대소문자를 구분하지 않는 일치가 발견되었는지 나타내는 불리언 리스트를 반환합니다.
containsword(["I have no words.", "words"], "Word") = [false, false]  
containsword(["word", "Words"], "Word") = [true, false]  
containsword(["Word", "Words in word"], "WORD") = [true, true]  

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

객체에서 여러 필드를 추출하여, 그 필드들만 가진 새로운 객체를 생성합니다.

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

sort(list)

리스트를 정렬하여, 정렬된 순서의 새로운 리스트를 반환합니다.

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

reverse(list)

리스트를 역순으로 하여, 역순된 새로운 리스트를 반환합니다.

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

length(object|array)

객체 내의 필드 수나 배열 내의 항목 수를 반환합니다.

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

nonnull(array)

모든 null 값을 제거한 새로운 배열을 반환합니다.

nonnull([]) = []  
nonnull([null, false]) = [false]  
nonnull([1, 2, 3]) = [1, 2, 3]

관련 링크

 

Functions - Dataview

Functions Dataview functions provide more advanced ways to manipulate data. You can use functions in data commands (except FROM) to filter or group or use them as additional information like TABLE columns or extra output for LIST queries to see your data i

blacksmithgu.github.io


 

반응형