blob: 7947baef2599146aa1ea01eb717423e8e17d89ff [file] [log] [blame]
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 1.8.1 from target/generated-site/markdown/udf.md at 2021-07-16
| Rendered using Apache Maven Fluido Skin 1.7
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20210716" />
<meta http-equiv="Content-Language" content="en" />
<title>AsterixDB &#x2013; User-defined Functions</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.7.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.7.min.js"></script>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left"><a href="./" id="bannerLeft"><img src="images/asterixlogo.png" alt="AsterixDB"/></a></div>
<div class="pull-right"></div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2021-07-16</li>
<li id="projectVersion" class="pull-right">Version: 0.9.7</li>
<li class="pull-right"><a href="index.html" title="Documentation Home">Documentation Home</a></li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span2">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Get Started - Installation</li>
<li><a href="ncservice.html" title="Option 1: using NCService"><span class="none"></span>Option 1: using NCService</a></li>
<li><a href="ansible.html" title="Option 2: using Ansible"><span class="none"></span>Option 2: using Ansible</a></li>
<li><a href="aws.html" title="Option 3: using Amazon Web Services"><span class="none"></span>Option 3: using Amazon Web Services</a></li>
<li class="nav-header">AsterixDB Primer</li>
<li><a href="sqlpp/primer-sqlpp.html" title="Using SQL++"><span class="none"></span>Using SQL++</a></li>
<li class="nav-header">Data Model</li>
<li><a href="datamodel.html" title="The Asterix Data Model"><span class="none"></span>The Asterix Data Model</a></li>
<li class="nav-header">Queries</li>
<li><a href="sqlpp/manual.html" title="The SQL++ Query Language"><span class="none"></span>The SQL++ Query Language</a></li>
<li><a href="SQLPP.html" title="Raw SQL++ Grammar"><span class="none"></span>Raw SQL++ Grammar</a></li>
<li><a href="sqlpp/builtins.html" title="Builtin Functions"><span class="none"></span>Builtin Functions</a></li>
<li class="nav-header">API/SDK</li>
<li><a href="api.html" title="HTTP API"><span class="none"></span>HTTP API</a></li>
<li><a href="csv.html" title="CSV Output"><span class="none"></span>CSV Output</a></li>
<li class="nav-header">Advanced Features</li>
<li><a href="aql/externaldata.html" title="Accessing External Data"><span class="none"></span>Accessing External Data</a></li>
<li><a href="feeds.html" title="Data Ingestion with Feeds"><span class="none"></span>Data Ingestion with Feeds</a></li>
<li class="active"><a href="#"><span class="none"></span>User Defined Functions</a></li>
<li><a href="sqlpp/filters.html" title="Filter-Based LSM Index Acceleration"><span class="none"></span>Filter-Based LSM Index Acceleration</a></li>
<li><a href="sqlpp/fulltext.html" title="Support of Full-text Queries"><span class="none"></span>Support of Full-text Queries</a></li>
<li><a href="sqlpp/similarity.html" title="Support of Similarity Queries"><span class="none"></span>Support of Similarity Queries</a></li>
<li><a href="interval_join.html" title="Support of Interval Joins"><span class="none"></span>Support of Interval Joins</a></li>
<li><a href="sqlpp/arrayindex.html" title="Support of Array Indexes"><span class="none"></span>Support of Array Indexes</a></li>
<li class="nav-header">Deprecated</li>
<li><a href="aql/primer.html" title="AsterixDB Primer: Using AQL"><span class="none"></span>AsterixDB Primer: Using AQL</a></li>
<li><a href="aql/manual.html" title="Queries: The Asterix Query Language (AQL)"><span class="none"></span>Queries: The Asterix Query Language (AQL)</a></li>
<li><a href="aql/builtins.html" title="Queries: Builtin Functions (AQL)"><span class="none"></span>Queries: Builtin Functions (AQL)</a></li>
</ul>
<hr />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="./" title="AsterixDB" class="builtBy"><img class="builtBy" alt="AsterixDB" src="images/asterixlogo.png" /></a>
</div>
</div>
</div>
<div id="bodyColumn" class="span10" >
<!--
! Licensed to the Apache Software Foundation (ASF) under one
! or more contributor license agreements. See the NOTICE file
! distributed with this work for additional information
! regarding copyright ownership. The ASF licenses this file
! to you under the Apache License, Version 2.0 (the
! "License"); you may not use this file except in compliance
! with the License. You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing,
! software distributed under the License is distributed on an
! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
! KIND, either express or implied. See the License for the
! specific language governing permissions and limitations
! under the License.
!-->
<h1>User-defined Functions</h1>
<div class="section">
<h2><a name="Table_of_Contents"></a><a name="atoc" id="#toc">Table of Contents</a></h2>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#installingUDF">Installing an UDF Library</a></li>
<li><a href="#UDFOnFeeds">Attaching an UDF on Data Feeds</a></li>
<li><a href="#udfConfiguration">A quick look of the UDF configuration</a></li>
<li><a href="#adapter">User defined Feed Adapters</a></li>
<li><a href="#uninstall">Unstalling an UDF Library</a><!--
! Licensed to the Apache Software Foundation (ASF) under one
! or more contributor license agreements. See the NOTICE file
! distributed with this work for additional information
! regarding copyright ownership. The ASF licenses this file
! to you under the Apache License, Version 2.0 (the
! "License"); you may not use this file except in compliance
! with the License. You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing,
! software distributed under the License is distributed on an
! "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
! KIND, either express or implied. See the License for the
! specific language governing permissions and limitations
! under the License.
!--></li>
</ul></div>
<div class="section">
<h2><a name="Introduction"></a><a name="introduction">Introduction</a></h2>
<p>Apache AsterixDB supports three languages for writing user-defined functions (UDFs): SQL++, Java, and Python A user can encapsulate data processing logic into a UDF and invoke it later repeatedly. For SQL++ functions, a user can refer to <a href="sqlpp/manual.html#Functions">SQL++ Functions</a> for their usages. This document will focus on UDFs in languages other than SQL++</p></div>
<div class="section">
<h2><a name="Endpoints_and_Authentication"></a><a name="authentication">Endpoints and Authentication</a></h2>
<p>The UDF API endpoint used to deploy functions is not enabled by default until authentication has been configured properly. Even if the endpoint is enabled, it is only accessible on the loopback interface on each NC to restrict access.</p>
<p>To enable it, we need to set the path to the credential file and populate it with our username and password.</p>
<p>The credential file is a simple <tt>/etc/passwd</tt> style text file with usernames and corresponding <tt>bcrypt</tt> hashed and salted passwords. You can populate this on your own if you would like, but the <tt>asterixhelper</tt> utility can write the entries as well. We can invoke <tt>asterixhelper</tt> like so:</p>
<div>
<div>
<pre class="source">$ bin/asterixhelper -u admin -p admin -cp opt/local/conf add_credential
</pre></div></div>
<p>Then, in your <tt>cc.conf</tt>, in the <tt>[cc]</tt> section, add the correct <tt>credential.file</tt> path</p>
<div>
<div>
<pre class="source">[nc]
address = 127.0.0.1
...
...
credential.file = conf/passwd
</pre></div></div>
<p>Now,restart the cluster if it was already started to allow the Cluster Controller to find the new credentials.</p></div>
<div class="section">
<h2><a name="Installing_a_Java_UDF_Library"></a><a name="installingUDF">Installing a Java UDF Library</a></h2>
<p>To install a UDF package to the cluster, we need to send a Multipart Form-data HTTP request to the <tt>/admin/udf</tt> endpoint of the CC at the normal API port (<tt>19004</tt> by default). Any suitable tool will do, but for the example here I will use <tt>curl</tt> which is widely available.</p>
<p>For example, to install a library with the following criteria:</p>
<ul>
<li><tt>udfs</tt> dataverse name</li>
<li>with a new Library name of <tt>testlib</tt></li>
<li>from <tt>lib.zip</tt> in the present working directory</li>
<li>to the cluster at <tt>localhost</tt> with API port <tt>19004</tt> of the Asterix CC</li>
<li>with credentials being a username and password of <tt>admin:admin</tt></li>
</ul>
<p>we would execute</p>
<div>
<div>
<pre class="source">curl -v -u admin:admin -X POST -F 'data=@./lib.zip' -F 'type=java' localhost:19004/admin/udf/udfs/testlib
</pre></div></div>
<p>Any response other than <tt>200</tt> indicates an error in deployment.</p>
<p>In the AsterixDB source release, we provide several sample UDFs that you can try out. You need to build the AsterixDB source to get the compiled UDF package. It can be found under the <tt>asterix-external-data</tt> sub-project under the path <tt>asterixdb/asterix-external-data/src/test/java/org/apache/asterix/external/library</tt>. After compilation, the UDFs will be packed in a zip file at <tt>asterixdb/asterix-external-data/target/asterix-external-data-$VERSION-testlib.zip</tt> which you can use to upload to the AsterixDB cluster.</p>
<p>Assuming that these UDFs have been installed into the <tt>testlib</tt> library in<tt>udfs</tt> dataverse, here is an example that uses the sample UDF <tt>mysum</tt> to compute the sum of two input integers.</p>
<div>
<div>
<pre class="source">USE udfs;
CREATE FUNCTION mysum(a: int32, b: int32)
RETURNS int32
AS &quot;org.apache.asterix.external.library.MySumFactory&quot; AT testlib;
</pre></div></div>
</div>
<div class="section">
<h2><a name="Creating_a_Python_UDF"></a><a name="PythonUDF" id="PythonUDF">Creating a Python UDF</a></h2>
<p>Python UDFs need to be rolled into a <a class="externalLink" href="https://github.com/linkedin/shiv">shiv</a> package with all their dependencies. By default AsterixDB will use the Python interpreter located at <tt>/usr/bin/python3</tt>. This can be changed in the cluster config <tt>[common]</tt> section using the <tt>python.path</tt> configuration variable.</p>
<p>First, let&#x2019;s devise a function that we would like to use in AsterixDB, <tt>sentiment_mod.py</tt></p>
<div>
<div>
<pre class="source">import os
from typing import Tuple
class sent_model:
def __init__(self):
good_words = os.path.join(os.path.dirname(__file__), 'good.txt')
with open(good_words) as f:
self.whitelist = f.read().splitlines()
def sentiment(self, arg: Tuple[str])-&gt; str:
words = arg[0].split()
for word in words:
if word in self.whitelist:
return 'great'
return 'eh'
</pre></div></div>
<p>Furthermore, let&#x2019;s assume &#x2018;good.txt&#x2019; contains the following entries</p>
<div>
<div>
<pre class="source">spam
eggs
ham
</pre></div></div>
<p>Now, in the module directory, execute <tt>shiv</tt> with all the dependencies of the module listed. We don&#x2019;t actually use scikit-learn here (our method is obviously better!), but it&#x2019;s just included as an example of a real dependency.</p>
<div>
<div>
<pre class="source">shiv -o lib.pyz --site-packages . scikit-learn
</pre></div></div>
<p>Then, deploy it the same as the Java UDF was, with the library name <tt>pylib</tt> in <tt>udfs</tt> dataverse</p>
<div>
<div>
<pre class="source">curl -v -u admin:admin -X POST -F 'data=@./lib.pyz' -F 'type=python' localhost:19002/admin/udf/udfs/pylib
</pre></div></div>
<p>With the library deployed, we can define a function within it for use. For example, to expose the Python function <tt>sentiment</tt> in the module <tt>sentiment_mod</tt> in the class <tt>sent_model</tt>, the <tt>CREATE FUNCTION</tt> would be as follows</p>
<div>
<div>
<pre class="source">USE udfs;
CREATE FUNCTION sentiment(a)
RETURNS TweetType
AS &quot;sentiment_mod&quot;, &quot;sent_model.sentiment&quot; AT pylib;
</pre></div></div>
<p>By default, AsterixDB will treat all external functions as deterministic. It means the function must return the same result for the same input, irrespective of when or how many times the function is called on that input. This particular function behaves the same on each input, so it satisfies the deterministic property. This enables better optimization of queries including this function. If a function is not deterministic then it should be declared as such by using a <tt>WITH</tt> sub-clause:</p>
<div>
<div>
<pre class="source">USE udfs;
CREATE FUNCTION sentiment(text)
AS &quot;sentiment_mod&quot;, &quot;sent_model.sentiment&quot; AT pylib
WITH { &quot;deterministic&quot;: false }
</pre></div></div>
<p>With the function now defined, it can then be used as any other scalar SQL++ function would be. For example:</p>
<div>
<div>
<pre class="source">USE udfs;
INSERT INTO Tweets([
{&quot;id&quot;:1, &quot;msg&quot;:&quot;spam is great&quot;},
{&quot;id&quot;:2, &quot;msg&quot;:&quot;i will not eat green eggs and ham&quot;},
{&quot;id&quot;:3, &quot;msg&quot;:&quot;bacon is better&quot;}
]);
SELECT t.msg as msg, sentiment(t.msg) as sentiment
FROM Tweets t;
</pre></div></div>
</div>
<div class="section">
<h2><a name="Python_Type_Mappings"></a><a name="pytpes">Python Type Mappings</a></h2>
<p>Currently only a subset of AsterixDB types are supported in Python UDFs. The supported types are as follows:</p>
<ul>
<li>Integer types (int8,16,32,64)</li>
<li>Floating point types (float, double)</li>
<li>String</li>
<li>Boolean</li>
<li>Arrays, Sets (cast to lists)</li>
<li>Objects (cast to dict)</li>
</ul>
<p>Unsupported types can be cast to these in SQL++ first in order to be passed to a Python UDF</p></div>
<div class="section">
<h2><a name="Execution_Model_For_UDFs"></a><a name="execution">Execution Model For UDFs</a></h2>
<p>AsterixDB queries are deployed across the cluster as Hyracks jobs. A Hyracks job has a lifecycle that can be simplified for the purposes of UDFs to - A pre-run phase which allocates resources, <tt>open</tt> - The time during which the job has data flowing through it, <tt>nextFrame</tt> - Cleanup and shutdown in <tt>close</tt>.</p>
<p>If a SQL++ function is defined as a member of a class in the library, the class will be instantiated during <tt>open</tt>. The class will exist in memory for the lifetime of the query. Therefore if your function needs to reference files or other data that would be costly to load per-call, making it a member variable that is initialized in the constructor of the object will greatly increase the performance of the SQL++ function.</p>
<p>For each function invoked during a query, there will be an independent instance of the function per data partition. This means that the function must not assume there is any global state or that it can assume things about the layout of the data. The execution of the function will be parallel to the same degree as the level of data parallelism in the cluster.</p>
<p>After initialization, the function bound in the SQL++ function definition is called once per tuple during the query execution (i.e. <tt>nextFrame</tt>). Unless the function specifies <tt>null-call</tt> in the <tt>WITH</tt> clause, <tt>NULL</tt> values will be skipped.</p>
<p>At the close of the query, the function is torn down and not re-used in any way. All functions should assume that nothing will persist in-memory outside of the lifetime of a query, and any behavior contrary to this is undefined.</p></div>
<div class="section">
<h2><a name="Attaching_a_UDF_on_Data_Feeds"></a><a name="UDFOnFeeds" id="UDFOnFeeds">Attaching a UDF on Data Feeds</a></h2>
<p>In <a href="feeds.html">Data Ingestion using feeds</a>, we introduced an efficient way for users to get data into AsterixDB. In some use cases, users may want to pre-process the incoming data before storing it into the dataset. To meet this need, AsterixDB allows the user to attach a UDF onto the ingestion pipeline. Following the example in <a href="feeds.html">Data Ingestion</a>, here we show an example of how to attach a UDF that extracts the user names mentioned from the incoming Tweet text, storing the processed Tweets into a dataset.</p>
<p>We start by creating the datatype and dataset that will be used for the feed and UDF. One thing to keep in mind is that data flows from the feed to the UDF and then to the dataset. This means that the feed&#x2019;s datatype should be the same as the input type of the UDF, and the output datatype of the UDF should be the same as the dataset&#x2019;s datatype. Thus, users should make sure that their datatypes are consistent in the UDF configuration. Users can also take advantage of open datatypes in AsterixDB by creating a minimum description of the data for simplicity. Here we use open datatypes:</p>
<div>
<div>
<pre class="source">USE udfs;
CREATE TYPE TweetType IF NOT EXISTS AS OPEN {
id: int64
};
CREATE DATASET ProcessedTweets(TweetType) PRIMARY KEY id;
</pre></div></div>
<p>As the <tt>TweetType</tt> is an open datatype, processed Tweets can be stored into the dataset after they are annotated with an extra attribute. Given the datatype and dataset above, we can create a Twitter Feed with the same datatype. Please refer to section <a href="feeds.html">Data Ingestion</a> if you have any trouble in creating feeds.</p>
<div>
<div>
<pre class="source">USE udfs;
CREATE FEED TwitterFeed WITH {
&quot;adapter-name&quot;: &quot;push_twitter&quot;,
&quot;type-name&quot;: &quot;TweetType&quot;,
&quot;format&quot;: &quot;twitter-status&quot;,
&quot;consumer.key&quot;: &quot;************&quot;,
&quot;consumer.secret&quot;: &quot;************&quot;,
&quot;access.token&quot;: &quot;**********&quot;,
&quot;access.token.secret&quot;: &quot;*************&quot;
};
</pre></div></div>
<p>Then we define the function we want to apply to the feed</p>
<div>
<div>
<pre class="source">USE udfs;
CREATE FUNCTION addMentionedUsers(t: TweetType)
AS &quot;org.apache.asterix.external.library.AddMentionedUsersFactory&quot; AT testlib
WITH { &quot;resources&quot;: { &quot;textFieldName&quot;: &quot;text&quot; } };
</pre></div></div>
<p>After creating the feed, we attach the UDF onto the feed pipeline and start the feed with following statements:</p>
<div>
<div>
<pre class="source">USE udfs;
CONNECT FEED TwitterFeed TO DATASET ProcessedTweets APPLY FUNCTION addMentionedUsers;
START FEED TwitterFeed;
</pre></div></div>
<p>You can check the annotated Tweets by querying the <tt>ProcessedTweets</tt> dataset:</p>
<div>
<div>
<pre class="source">SELECT * FROM ProcessedTweets LIMIT 10;
</pre></div></div>
</div>
<div class="section">
<h2><a name="Installing_a_user-defined_Feed_Adapter"></a><a name="adapter">Installing a user-defined Feed Adapter</a></h2>
<p>First, upload a zip file packaged the same way as a Java UDF, but also containing the adapter you would like to use. Next, issue a <tt>CREATE ADAPTER</tt> statement referencing the class name. For example:</p>
<div>
<div>
<pre class="source">CREATE ADAPTER TweetAdapter
AS &quot;org.apache.asterix.external.library.adapter.TestTypedAdapterFactory&quot; AT testlib;
</pre></div></div>
<p>Then, the adapter can be used like any other adapter in a feed.</p>
<div>
<div>
<pre class="source">CREATE FEED TweetFeed WITH {
&quot;adapter-name&quot;: &quot;TweetAdapter&quot;,
&quot;type-name&quot; : &quot;TweetType&quot;,
&quot;num_output_records&quot;: 4
};
</pre></div></div>
</div>
<div class="section">
<h2><a name="Unstalling_an_UDF_Library"></a><a name="uninstall">Unstalling an UDF Library</a></h2>
<p>If you want to uninstall the UDF library, simply issue a <tt>DELETE</tt> against the endpoint you <tt>POST</tt>ed against once all functions declared with the library are removed. First we&#x2019;ll drop the function we declared earlier:</p>
<div>
<div>
<pre class="source">USE udfs;
DROP FUNCTION mysum(a,b);
</pre></div></div>
<p>Then issue the proper <tt>DELETE</tt> request</p>
<div>
<div>
<pre class="source">curl -u admin:admin -X DELETE localhost:19002/admin/udf/udfs/testlib
</pre></div></div>
<p>The library will also be dropped if you drop the dataverse entirely.</p></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<div class="row-fluid">Apache AsterixDB, AsterixDB, Apache, the Apache
feather logo, and the Apache AsterixDB project logo are either
registered trademarks or trademarks of The Apache Software
Foundation in the United States and other countries.
All other marks mentioned may be trademarks or registered
trademarks of their respective owners.
</div>
</div>
</div>
</footer>
</body>
</html>