code: def pivot_query_as_matrix(facet=None, facet_pivot_fields=None, **kwargs):
      
      if facet_pivot_fields is None:
          facet_pivot_fields = []
      logging.info("Additional args: {}".format(kwargs))
      fp = search_associations(rows=0,
                               facet_fields=[facet],
                               facet_pivot_fields=facet_pivot_fields,
                               **kwargs)['facet_pivot']
  
      # we assume only one
      results = list(fp.items())[0][1]
      tups = []
      xtype=None
      ytype=None
      xlabels=set()
      ylabels=set()
  
      
      for r in results:
          logging.info("R={}".format(r))
          xtype=r['field']
          rv = r['value']
          xlabels.add(rv)
          for piv in r['pivot']:
              ytype=piv['field']
              pv = piv['value']
              ylabels.add(pv)
              tups.append( (rv,pv,piv['count']) )
  
      z = [ [0] * len(xlabels) for i1 in range(len(ylabels)) ]
  
      xlabels=list(xlabels)
      ylabels=list(ylabels)
      xmap = dict([x[::-1] for x in enumerate(xlabels)])
      ymap = dict([x[::-1] for x in enumerate(ylabels)])
      for t in tups:
          z[ymap[t[1]]][xmap[t[0]]] = t[2]
      m = {'xtype':xtype,
           'ytype':ytype,
           'xaxis':xlabels,
           'yaxis':ylabels,
           'z':z}
      return m
docs: Pivot query