blob: 994c323a9020e7956e60cc2cbee0639cf5c9f531 [file] [log] [blame]
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 1.8.1 from target/generated-site/markdown/udf.md at 2020-12-06
| 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="20201206" />
<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: 2020-12-06</li>
<li id="projectVersion" class="pull-right">Version: 0.9.6-SNAPSHOT</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 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 endpoint is not enabled by default until authentication has been configured properly. To enable it, we will 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>19002</tt> by default). The request should use HTTP Basic authentication. This means your credentials will <i>not</i> be obfuscated or encrypted <i>in any way</i>, so submit to this endpoint over localhost or a network where you know your traffic is safe from eavesdropping. 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>19002</tt></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' localhost:19002/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>asterixdb-external</tt> sub-project. 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' 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 <tt>WITH</tt> sub-clause:</p>
<div>
<div>
<pre class="source">USE udfs;
CREATE FUNCTION sentiment(a)
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="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@2;
</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>